如何使word-wrapped文本缩放至适配div且无溢出?
实现文本自动放大至填满容器且不溢出
纯CSS近似方案
适合文本内容相对固定的场景,利用容器查询和clamp()函数结合容器宽高比例动态调整字体大小:
<html> <head> <style> div#hugetext { width: 250px; height: 500px; border: 1px solid blue; overflow-wrap: break-word; container-type: size; display: flex; align-items: center; padding: 8px; overflow: hidden; } @container (width >= 250px) and (height >= 500px) { #hugetext { /* clamp(最小字号, 动态计算值, 最大字号) */ font-size: clamp(16px, min(250px / 10, 500px / 5), 120px); line-height: 1.2; } } </style> </head> <body> <div id="hugetext">This text shall be so huge that it fills the entire div</div> </body> </html>
核心逻辑是用min()取容器宽、高分别计算出的字体基准值(除数对应预估的每行字符数、行数),再通过clamp()限制字号范围,避免溢出。可根据实际文本调整除数优化适配效果。
JavaScript精准方案
如果需要适配任意文本内容,确保完全填满容器且无溢出,用JS动态计算最优字号:
<html> <head> <style> div#hugetext { width: 250px; height: 500px; border: 1px solid blue; overflow-wrap: break-word; padding: 8px; overflow: hidden; } </style> </head> <body> <div id="hugetext">This text shall be so huge that it fills the entire div</div> <script> const textContainer = document.getElementById('hugetext'); let fontSize = 16; textContainer.style.fontSize = `${fontSize}px`; // 逐步增大字号,直到文本溢出容器 while (textContainer.scrollHeight <= textContainer.clientHeight && fontSize < 200) { fontSize++; textContainer.style.fontSize = `${fontSize}px`; } // 回退到最后一个不溢出的字号 fontSize--; textContainer.style.fontSize = `${fontSize}px`; </script> </body> </html>
这个方案通过循环检测文本的滚动高度与容器可视高度的关系,精准找到刚好填满容器的最大字号。若需同时适配宽度溢出,可在循环条件中加入textContainer.scrollWidth <= textContainer.clientWidth。
内容的提问来源于stack exchange,提问作者bugmenot123
相关产品推荐
相关产品推荐

