首页 > 解决方案 > 基于视口和文本长度的动态字体大小

问题描述

我有一个容器,其尺寸根据视口固定,容器内的文本是动态的:

HTML

<div class="my-container">
    <div>Dynamic length text</div>
</div>

CSS

.my-container {
    height: 25vh;
    width: 25vw;
    font-size: ???;
}

我需要font-size在这个容器内根据文本的字符数进行相应的缩放,以防止它溢出。理想情况下,文本会占用尽可能多的空间。

我用各种js / css片段尝试了几个小时,但似乎找不到解决方案。

标签: javascripthtmljquerycss

解决方案


目的是使文本适合,因此需要减小字体大小,直到高度小于或等于父 div 的高度。

实际上,目的是确保 div 的面积小于或等于其父 div。使用它可以稍微简化一些事情,在我们到达那里之前只需要很少的迭代。

const myContainer = document.querySelector('.my-container');
const div = myContainer.querySelector('div');
const w = myContainer.offsetWidth;
const h = myContainer.offsetHeight;
let fontSize = 25;
// put in an iteration count for the test just in case we end up in some awful loop with War annd Peace being squished in, though it should work in less than 10 anyway
let iterationCount = 0;
function resize() {
  iterationCount++;
  if (iterationCount <= 10) {
    const divw = div.offsetWidth;
    const divh = div.offsetHeight;
    const factor = Math.sqrt((w*h)/(divw*divh));
    if (divh > h) {
      fontSize = fontSize * factor;
      div.style.fontSize = fontSize + 'vw';
      resize();
    }
  }
}
resize();
.my-container {
    height: 25vh;
    width: 25vw;
    border-style: solid;
}
.my-container div {
    font-size: 25vw;
}
<div class="my-container">
    <div>
      Dynamic length text and a lot more here so we really overrun Dynamic length text and a lot more here so we really overrun Dynamic length text and a lot more here so we really overrun Dynamic length text and a lot more here so we really overrunDynamic length text and a lot more here so we really overrunDynamic length text and a lot more here so we really overrun Dynamic length text and a lot more here so we really overrun Dynamic length text and a lot more here so we really overrun
    </div>
</div>


推荐阅读