You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现文本自动调整字号以适配固定尺寸的div?

如何让固定尺寸的Div字号自动适配容器尺寸?

你需要实现的是:固定宽高的div中,文本过长时自动缩小字号避免溢出,文本较短时自动增大字号填满容器空间。以下是两种可行方案:

一、纯CSS近似方案(简单但不够精准)

利用CSS的clamp()函数结合容器尺寸比例,设置字号的最小、理想、最大值。这种方案不需要JS,适合对精度要求不高的场景:

<div
  style="background-color:aqua; overflow:hidden; width:10rem; height:3.5rem; font-size: clamp(1rem, calc(3.5rem / 1.5), 4rem); line-height:1.2;"
>
  Hello World
</div>
  • clamp(min, ideal, max):其中calc(3.5rem / 1.5)是基于容器高度计算的理想字号(除以1.5是预留行高空间),1rem是最小字号,4rem是最大字号
  • 缺点:无法根据实际文本长度动态调整,只是基于容器尺寸的比例适配

二、JavaScript精准方案(适配文本长度)

如果需要根据文本实际长度精准调整字号,就得用JS检测文本是否溢出,然后动态修改字号:

<div id="autoSizeText"
  style="background-color:aqua; overflow:hidden; width:10rem; height:3.5rem; font-size:4rem; line-height:1.2;"
>
  Hello World
</div>

<script>
const adjustFontSize = () => {
  const element = document.getElementById('autoSizeText');
  let fontSize = parseFloat(window.getComputedStyle(element).fontSize);
  const minFontSize = 16; // 最小字号(px)
  const maxFontSize = 64; // 最大字号(px,对应4rem)

  // 检查是否溢出
  const isOverflowing = () => {
    return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth;
  };

  // 先尝试增大到最大字号,再缩小到合适尺寸
  while (!isOverflowing() && fontSize < maxFontSize) {
    fontSize++;
    element.style.fontSize = `${fontSize}px`;
  }

  while (isOverflowing() && fontSize > minFontSize) {
    fontSize--;
    element.style.fontSize = `${fontSize}px`;
  }
};

// 初始化执行
adjustFontSize();
// 窗口 resize 时重新调整(可选)
window.addEventListener('resize', adjustFontSize);
</script>

代码说明:

  1. isOverflowing()函数通过比较元素的scrollHeight/scrollWidth和clientHeight/clientWidth判断文本是否溢出
  2. 先尝试把字号增大到最大值,直到文本溢出,再逐步缩小到刚好不溢出的尺寸
  3. 可以添加窗口resize事件,确保窗口变化时字号重新适配

内容的提问来源于stack exchange,提问作者Sherwin Variancia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:45:33