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

非等宽字体下,如何用CSS实现分页数字框按位数统一宽度?

分页数字框宽度统一问题

当前实现代码

CSS

.pagination-wrapper{
  display: flex;
  justify-content: center;
  padding-top: 50px;
}
.number{
  border: thin solid rgb(80 80 80);
  padding: 0.2rem 0.3rem 0.2rem 0.3rem;
  text-align: center;
  margin: 0 0.2rem;

  min-width: 1rem;
}

HTML

<div class="pagination-wrapper">
    <span class="number">1</span> 
    <span class="number">56</span> 
  <span class="number">111</span> 
  <span class="number">888</span> 
</div>

现状

已经通过min-width实现1位、2位数字的边框大小一致,效果符合预期。

问题

使用非等宽字体时,"111"这类窄三位数的数字框宽度明显小于"888"这类宽三位数。

需求

按数字位数统一对应宽度:1位、2位数字框用min-width(如16px),三位数统一24px,四位数统一32px等,不同位数的数字框无需大小一致。

已尝试的方法

  • 给字体族添加monospace属性无效,推测所用字体本身不是等宽字体;
  • 用JavaScript检测数字位数并设置不同min-width,但操作繁琐。

使用Bootstrap 3框架,该问题在无框架环境同样存在。

纯CSS解决方案

不需要JavaScript,也不用更换字体,有两种可行方式:

方式一:利用CSS ch单位 + :has()伪类

ch单位代表当前字体中数字"0"的宽度,能精准匹配数字宽度需求:

.pagination-wrapper{
  display: flex;
  justify-content: center;
  padding-top: 50px;
}
.number{
  border: thin solid rgb(80 80 80);
  padding: 0.2rem 0.3rem;
  text-align: center;
  margin: 0 0.2rem;
  /* 1、2位数字保留min-width,基于1个0的宽度加内边距 */
  min-width: calc(1ch + 0.6rem);
}
/* 三位数设置固定宽度:3个0的宽度加左右内边距总和 */
.number:has(:nth-child(1):nth-last-child(3)) {
  width: calc(3ch + 0.6rem);
}
/* 四位数同理 */
.number:has(:nth-child(1):nth-last-child(4)) {
  width: calc(4ch + 0.6rem);
}

方式二:给不同位数的数字框添加类(兼容老浏览器)

如果需要兼容不支持:has()的浏览器,可在生成HTML时给数字框按位数加类,再写对应CSS:

修改后的HTML

<div class="pagination-wrapper">
    <span class="number digit-1">1</span> 
    <span class="number digit-2">56</span> 
  <span class="number digit-3">111</span> 
  <span class="number digit-3">888</span> 
</div>

对应的CSS

.pagination-wrapper{
  display: flex;
  justify-content: center;
  padding-top: 50px;
}
.number{
  border: thin solid rgb(80 80 80);
  padding: 0.2rem 0.3rem;
  text-align: center;
  margin: 0 0.2rem;
}
.number.digit-1, .number.digit-2 {
  min-width: calc(1ch + 0.6rem);
}
.number.digit-3 {
  width: calc(3ch + 0.6rem);
}
.number.digit-4 {
  width: calc(4ch + 0.6rem);
}

原理说明

ch单位基于当前字体中"0"的宽度,n位数字用nch加上左右内边距的总和,就能让同位数的数字框宽度完全一致,不受单个数字宽窄影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:50:25