基于视口和文本长度的动态字体大小



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

HTML

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

CSS

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

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

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

目的是使文本适合,因此需要减小字体大小,直到高度小于或等于父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>

最新更新