【问题标题】:Fit text inside a fixed height and fixed width div by reducing the font size [duplicate]通过减小字体大小使文本适合固定高度和固定宽度的 div [重复]
【发布时间】:2020-02-10 06:16:01
【问题描述】:

你们提到的所有那些重复只处理 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/

【问题讨论】:

    标签: javascript html css font-size


    【解决方案1】:

    您可以通过使用 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-27
      • 2010-12-16
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2017-07-18
      相关资源
      最近更新 更多