我很难理解字体缩放。

我目前有一个字体大小为100%的网站。但这是100%的吗?这似乎是在16个像素处计算出来的。

我的印象是,100%会以某种方式指代浏览器窗口的大小,但显然不是因为无论窗口大小调整为移动宽度还是宽屏桌面,都是16像素。

如何使站点上的文本与其容器相关?我尝试过使用它们,但这也无法扩展。

我的理由是,当你调整大小时,像我的菜单这样的东西会变得压扁,所以我需要减少.menuItem等元素相对于容器宽度的px字体大小。(例如,在大型桌面上的菜单中,22px的效果非常好。向下移动到平板电脑宽度,16px更合适。)

我知道我可以添加断点,但我真的希望文本能够缩放并具有额外的断点,否则,我将以每100像素宽度减少数百个断点来控制文本。


当前回答

我想喜欢接受的答案,但从根本上说,符合我的标准的答案都需要使用图书馆。我决定编写一个非常适合我的简单函数,而不是让自己熟悉另一个库,然后找出如何使用它并准备在它不工作时进行调试。

理论:

传入需要匹配的字符串传入要从中继承文本样式的父级可选地传入自定义属性(例如,您将从中继承字体和其他属性的类/id,或者仅传入自定义内联样式)函数将在屏幕外创建一个文本元素,其中包含该文本、该父元素和这些属性,字体大小为1px,并对其进行测量然后,在循环中,它将逐像素增加字体大小,直到超过宽度限制;一旦完成,它将返回最后一个合适的然后删除测试元素当然,这一切都发生在眨眼之间

限制:

我不在乎动态调整屏幕大小,因为这与我的上下文无关。在生成文本时,我只关心运行时的屏幕大小。我依赖一个小助手函数,我也在代码的其他地方使用它,它基本上作为mithril.js的单函数版本存在;老实说,我几乎在每个项目中都使用这个小功能,它值得自己学习。

  function findMaxFontSize(
    string="a string", 
    parent=document.body, 
    attributes={id:'font-size-finder',class:'some-class-with-font'}
  ) {
    // by using parent, we can infer the same font inheritance;
    // you can also manually specify fonts or relevant classes/id with attributes if preferred/needed
    attributes.style = 'position:absolute; left:-10000; font-size:1px;' + (attributes.style || "");
    let testFontEl = createEl('p', attributes, string);
    parent.appendChild(testFontEl);
    let currentWidth = testFontEl.offsetWidth;
    let workingFontSize = 1;
    let i = 0;
    while (currentWidth < maxWidth && i < 1000) {
      testFontEl.style.fontSize = Number(testFontEl.style.fontSize.split("px")[0]) + 1 + "px";
      currentWidth = testFontEl.offsetWidth;
      if (currentWidth < maxWidth) {
        workingFontSize = testFontEl.style.fontSize;
      }
      i++; // safety to prevent infinite loops
    }
    console.log("determined maximum font size:",workingFontSize,'one larger would produce',currentWidth,'max width allowed is',maxWidth,'parent is',parent);
    parent.removeChild(testFontEl);
    return workingFontSize.split("px")[0];
  }
// utility function, though you could easily modify the function above to work without this.
  // normally these have no default values specified, but adding them here
  // to make usage clearer.
  function createEl(tag="div", attrs={class:'some-class'}, children=[]) {
    let el = document.createElement(tag);
    if (attrs) {
      Object.keys(attrs).forEach(attr => {
        el.setAttribute(attr, attrs[attr])
      })
    }
    if (children) {
      children = Array.isArray(children) ? children : [children];
      for (let child of children) {
        if (typeof child === "number") child = ""+child;
        if (typeof child === "string") {
          el.insertAdjacentText("afterbegin", child);
        }
        else {
          try {
            el.appendChild(child)
          } catch (e) {
            debugger
          }
        }
      }
    }
    return el;
  };

use:

    const getUsername = () => "MrHarry";
    const username = getUsername();
    const anchor = document.querySelector('.container');
    const titleFontSize = findMaxFontSize(`Welcome, ${username}`, anchor, {style:'font-weight:900;'});
    const titleFontStyle = `font-size:${titleFontSize}px;`;  

其他回答

这可能不太实用,但如果您希望字体是父级的直接函数,而不需要任何JavaScript侦听/循环(interval)来读取div/页面的大小,那么有一种方法可以做到。Iframes。

iframe中的任何内容都会将iframe的大小视为视口的大小。因此,诀窍是创建一个iframe,其宽度是您希望文本达到的最大宽度,其高度等于特定文本的最大高度*纵横比。

抛开视口单位不能与文本的父单位一起出现的限制(如中所示,具有与其他所有单位相同的%大小),视口单位确实提供了一个非常强大的工具:能够获得最小/最大尺寸。你不能在其他地方这样做-你不能说。。。使这个div的高度等于父对象的宽度。

也就是说,诀窍是使用vmin,并设置iframe大小,当高度是限制维度时,[fract]*总高度是一个好的字体大小,而当宽度是限制维度的时候,[fract]*总宽度。这就是为什么高度必须是宽度和纵横比的乘积。

对于我的特定示例

.main iframe{
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  height: calc(3.5 * 100%);
  background: rgba(0, 0, 0, 0);
  border-style: none;
  transform: translate3d(-50%, -50%, 0);
}

这种方法的一个小烦恼是,您必须手动设置iframe的CSS。如果您附加整个CSS文件,这将占用许多文本区域的大量带宽。所以,我所做的是直接从CSS中附加我想要的规则。

var rule = document.styleSheets[1].rules[4];
var iDoc = document.querySelector('iframe').contentDocument;
iDoc.styleSheets[0].insertRule(rule.cssText);

您可以编写一个小函数来获取CSS规则/所有影响文本区域的CSS规则。

如果没有一些循环/聆听JavaScript,我想不出另一种方法。真正的解决方案是让浏览器提供一种根据父容器缩放文本的方式,并提供相同的vmin/vmax类型功能。

JSFiddle:https://jsfiddle.net/0jr7rrgm/3/(单击一次可将红色方块锁定在鼠标上,再次单击可释放)

大部分JavaScript都是我自定义的点击拖动功能。

SVG解决方案:

.树脂土{调整大小:两者;边距:0;填充:0;高度:75px;宽度:500px;背景色:浅蓝色;溢出:隐藏;}<div class=“resizeme”><svg宽度=“100%”高度=“100%”viewBox=“0 0 500 75”preserveAspectRatio=“xMinYMid满足”style=“背景色:绿色”xmlns=“http://www.w3.org/2000/svg"xmlns:xlink=“http://www.w3.org/1999/xlink"><文本x=“0”y=“75”font size=“75”fill=“黑色”>█调整此大小█</文本></svg></div>

使用foreignObject的SVG和文本换行解决方案:

.树脂土{调整大小:两者;边距:0;填充:0;高度:200px;宽度:500px;背景色:浅蓝色;溢出:隐藏;}<div class=“resizeme”><svg宽度=“100%”高度=“100%”viewBox=“0 0 500 200”preserveAspectRatio=“xMinYMin满足”><foreignObject width=“100%”height=“100%”xmlns=“http://www.w3.org/1999/xhtml"><div xmlns=“http://www.w3.org/1999/xhtml“style=”背景色:浅绿色;"><h1>标题</h1><p>调整蓝色框的大小</p></div></foreignObject></svg></div>

这个呢?将父级的字体大小设置为等于其宽度,然后使用文本元素字体大小的百分比。

.element {
    width: 400px;
    font-size: 400px; /* equal to width */
}

.text {
    width: 10%;  /* will be 40px */
}

我发现这非常简单,特别是当你处理图标时,但也适用于文本。

/*造型的开始*/* {边距:0;填充:0;框大小调整:边框框;}.box格式{显示:块;背景:矢车菊蓝;高度:最大含量;边距底部:32px;}/*样式结束*/.方框p{字体大小:20%;}<div class=“box”style=“width:400px;font-size:400px”><p>文本</p></div><div class=“box”style=“width:128px;font-size:128px”><p>文本</p></div><div class=“box”style=“width:10vw;font-size:10vw”><p>文本</p></div><div class=“box”style=“width:64px;font-size:64px”><p>文本</p></div>

这对我有用:

我尝试根据设置“字体大小:10px”得到的宽度/高度来近似字体大小。基本上,这个想法是“如果我有20像素宽和11像素高的‘字体大小:10px’,那么计算50像素宽和30像素高的容器的最大字体大小是多少?”

答案是双重比例制:

{20:10=50:X,11:10=30:Y}={X=(10*50)/20,Y=(10*30)/11}

现在X是与宽度匹配的字体大小,Y是与高度匹配的字体尺寸;取最小值

function getMaxFontSizeApprox(el){
    var fontSize = 10;
    var p = el.parentNode;

    var parent_h = p.offsetHeight ? p.offsetHeight : p.style.pixelHeight;
    if(!parent_h)
        parent_h = 0;

    var parent_w = p.offsetHeight ? p.offsetWidth : p.style.pixelWidth;
    if(!parent_w)
        parent_w = 0;

    el.style.fontSize = fontSize + "px";

    var el_h = el.offsetHeight ? el.offsetHeight : el.style.pixelHeight;
    if(!el_h)
        el_h = 0;

    var el_w = el.offsetHeight ? el.offsetWidth : el.style.pixelWidth;
    if(!el_w)
        el_w = 0;

    // 0.5 is the error on the measure that JavaScript does
    // if the real measure had been 12.49 px => JavaScript would have said 12px
    // so we think about the worst case when could have, we add 0.5 to 
    // compensate the round error
    var fs1 = (fontSize*(parent_w + 0.5))/(el_w + 0.5);
    var fs2 = (fontSize*(parent_h) + 0.5)/(el_h + 0.5);

    fontSize = Math.floor(Math.min(fs1,fs2));
    el.style.fontSize = fontSize + "px";
    return fontSize;
}

注意:函数的参数必须是span元素或小于其父元素的元素,否则如果子元素和父元素都具有相同的宽度/高度,则函数将失败。

使用vw,em&co.确实有效,但IMO始终需要人为的微调。

这是我刚刚根据@tnt-rox的回答编写的一个脚本,它试图使人类的触摸自动化:

$('#controller').click(function(){$('h2').each(函数){变量$el=$(此),max=$el.get(0),el=空;最大值=最大值? 最大偏移宽度: 320;$el.css({“font size”:“1em”,“display”:“inline”,});el=$el.get(0);el.get_float=函数(){变量fs=0;if(this.style&&this.style.fontSize){fs=parseFloat(this.style.fontSize.replace(/([\d\.]+)em/g,'$1'));}返回fs;};el.bigger=函数(){this.style.fontSize=(this.get_float()+0.1)+'em';};而(el.offsetWidth<max){el.bigger();}//完成触摸。$el.css({“字体大小”:((el.get_float()-0.1)+'em'),'线条高度':'正常','显示':'',});}); // 结束(每个)}); // 结束(字体缩放测试)第二部分{宽度:50%;背景色:番茄;字体系列:'Arial';}氢气{空白:nowrap;}h2:第n个孩子(2){字体样式:斜体;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js“></script><input type=“button”id=“controller”value=“Apply”/><div><h2>Lorem ipsum dolor公司</h2><h2>测试字符串</h2><h2>甜蜜串联</h2><h2>字体缩放比例</h2></div>

它基本上将字体大小减小到1em,然后开始递增0.1,直到达到最大宽度。

JSFiddle公司