用等宽字体填充固定大小的div

时间:2016-10-02 22:22:05

标签: javascript html css fonts

想象一下,有一串字符和一个固定大小的HTML div元素。通过使用等宽字体和给定的固定字体大小,字符串中的多少个字符适合div(不包装)? 奖励:如何最终稍微调整字体大小,使文本真正占据容器的整个宽度。

JS

var s = "skjhfkjsdhjfksdhjkghskjgh...";

CSS

#c { width:267px; font-size:30px; font-family:monospace }

HTML

<div id="c"></div>

对于一种即兴的方法,请看这个小提琴,它起作用但我认为不是那么干净。可能有更好的方法:https://jsfiddle.net/6et20853/1/

1 个答案:

答案 0 :(得分:1)

您需要.getBoundingClientRect包含一个等宽字符的元素才能获得一个字符的宽度:

&#13;
&#13;
oneCharWidth = document.querySelector('#testing').getBoundingClientRect().width;
console.log(oneCharWidth)
&#13;
<span id="testing" style="font-family: monospace">a</span>
&#13;
&#13;
&#13;

如果要检查哪种字体大小允许一串文本适合固定大小的容器:

&#13;
&#13;
var widthOfContainer = 400, // The width of the container in pixels
    textLength = "Hello world!".length, // The text to fit
    testElem = document.querySelector('#testing'),
    widthOfChar,
    fontSize = 100; // Our initial guess (must be exaggerated, otherwise optimal value won't be reached)

do {
  fontSize--;
  testElem.style.fontSize = fontSize + 'px';
  widthOfChar = testElem.getBoundingClientRect().width;
} while (textLength * widthOfChar > widthOfContainer);

var container = document.querySelector('#container');
container.style.fontSize = fontSize + 'px';

testElem.parentNode.removeChild(testElem); // Remove #testing element
&#13;
#container {
  border: 1px solid red;
  font-family: monospace;
  width: 400px;
}

#testing {
  font-family: monospace;
}
&#13;
<div id="container">Hello world!</div>
<span id="testing">a</span>
&#13;
&#13;
&#13;

相关问题