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

使用Georgia等可变宽度字体时,如何避免单数字变化的内容跳动

解决Georgia字体数字跳动问题

核心原因是Georgia属于比例字体(proportional font),不同数字的宽度存在差异;而你提到的sans类字体大多默认使用等宽数字(tabular figures),因此不会出现跳动。要在保留Georgia字体的同时避免单数字变化时的跳动,以下是两种可行方案:

方法1:使用CSS font-variant-numeric: tabular-nums

这是最简洁高效的方案,现代浏览器均支持该属性。启用后,Georgia的数字会切换为等宽样式,单数字切换时宽度保持不变,只有位数增加(如9→10)时才会自然扩展,完全符合你的需求。

修改后的完整代码

HTML

<div>
  <div class="flex items-center">
    <div class="flex-1">
      <div class="bg-blue"></div>
    </div>
    <div class='font-serif'>
      <time id="time">0</time>
    </div>
  </div>
  <button id="start">start</button>
</div>

CSS

.flex-1 {
  flex: 1 1 0%;
}

.flex {
  display: flex;
}

.font-serif {
  font-family: Georgia;
  /* 启用等宽数字变体 */
  font-variant-numeric: tabular-nums;
}

.items-center {
  align-items: center;
}

.bg-blue {
  background: blue;
  width: 100%;
  height: 100px;
}

JavaScript

document.querySelector('#start').addEventListener("click", function() {
  setInterval(() => {
    document.querySelector('#time').innerHTML++ 
  }, 100) 
});

方法2:降级兼容方案(针对极旧浏览器)

如果需要兼容不支持font-variant-numeric的旧浏览器,可以将每个数字单独用<span>包裹,给每个span设置统一的最小宽度并右对齐,确保单数字切换时宽度稳定,位数增加时容器自然扩展。

修改后的完整代码

HTML

<div>
  <div class="flex items-center">
    <div class="flex-1">
      <div class="bg-blue"></div>
    </div>
    <div class='font-serif counter-container'>
      <time id="time"><span>0</span></time>
    </div>
  </div>
  <button id="start">start</button>
</div>

CSS

.flex-1 {
  flex: 1 1 0%;
}

.flex {
  display: flex;
}

.font-serif {
  font-family: Georgia;
}

.counter-container span {
  display: inline-block;
  min-width: 1.2em; /* 根据字体大小调整,确保容纳最宽数字 */
  text-align: right;
}

.items-center {
  align-items: center;
}

.bg-blue {
  background: blue;
  width: 100%;
  height: 100px;
}

JavaScript

document.querySelector('#start').addEventListener("click", function() {
  const timeEl = document.querySelector('#time');
  setInterval(() => {
    const num = parseInt(timeEl.textContent) + 1;
    // 将数字拆分为单独的span元素
    timeEl.innerHTML = num.toString().split('').map(digit => `<span>${digit}</span>`).join('');
  }, 100) 
});

内容的提问来源于stack exchange,提问作者Bernard Wiesner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:06:16