通过减小字体大小将文本适合在固定高度和固定宽度div内

时间:2019-10-13 11:04:47

标签: javascript html css font-size

你们提到的所有重复项仅处理div的宽度。我还需要解决div的高度。因此,内容也不能超出div的高度范围。我尝试了所有类似的问题及其答案,但都没有包含文字,文字总是高度溢出。

我尝试过的问题示例: 1. Font scaling based on width of container 2. resize font-size according to div size

现在要提问。

我的div具有固定的高度和宽度。我需要文本来减小字体大小,因为文本内容的长度会增加,以便溢出。我在这里看到了其他几个仅涉及div宽度的问题。因此,有了这些解决方案,我的文字就会垂直溢出。

我真的不在乎解决方案是使用CSS还是javascript。感谢您的提前帮助。

这是我试图使其工作的代码:

<div class="box">
  <span>
    This is a really long sentence to demonstrate how it doesn't fit inside the box and doesn't do what I want.
  </span>
</div>

.box {
  margin: 10px;
  width: 200px;
  height: 50px;
  border: 1px solid black;
}

这里是jsfiddle:https://jsfiddle.net/wnkzy0u8/1/

1 个答案:

答案 0 :(得分:0)

您可以通过使用Javascript函数计算正确的字体大小来做到这一点:

const box = document.getElementById('box')
const text = document.getElementById('text');

const boxHeight = parseInt(window.getComputedStyle(box).height);

const getTextHeight = () => parseInt(window.getComputedStyle(text).height);
const getTextFontSize = () => parseInt(window.getComputedStyle(text).fontSize);

while (getTextHeight() > boxHeight) {
  text.style.fontSize = getTextFontSize() - 1 + 'px'
}
.box {
  margin: 10px;
  width: 200px;
  height: 50px;
  border: 1px solid black;
}
<div id="box" class="box">
  <div id="text">
    This is a really long sentence to demonstrate how it doesn't fit inside the box and doesn't do what I want.
  </div>
</div>