CSS 计数器

给列表做“1、2、3”自动编号,用 ol 就能实现;但章节号、嵌套层级这类复杂编号,HTML 就无能为力了。CSS 计数器(Counters)能在样式层自动计数并拼出编号,无需改动任何结构。本节讲解 counter-reset、counter-increment 与 content 三个核心属性的配合。

三个核心属性

计数器由三步配合完成——初始化、累加、显示:

  • counter-reset: 名:把计数器归零,可一次初始化多个,如 counter-reset: a b;
  • counter-increment: 名:元素每匹配一次,计数器加 1。
  • content: counter(名):把当前计数值作为伪元素内容显示出来。
body { counter-reset: section; }            /* 1. 初始化名为 section 的计数器 */
h2::before {
    counter-increment: section;             /* 2. 每遇到一个 h2 就 +1 */
    content: "第 " counter(section) " 章 "; /* 3. 显示当前值 */
}

效果:每个 h2 前自动出现“第 1 章”“第 2 章”……手动增删章节也无需改编号。

为列表自动编号

不想用默认圆点或数字时,可关掉 list-style 自己拼出带前缀的编号:

ol { list-style: none; counter-reset: item; } /* 去掉默认数字 */
ol li::before {
    counter-increment: item;                  /* 每次 +1 */
    content: "步骤 " counter(item) ":";      /* 拼出自定义编号 */
    color: #e67e22;
    font-weight: bold;
}
<ol>
  <li>准备材料</li>
  <li>混合搅拌</li>
  <li>装盘上桌</li>
</ol>

效果:列表显示为“步骤 1:准备材料”“步骤 2:混合搅拌”……默认数字被完全替换,且新增 li 后编号自动顺延。

嵌套计数 counters()

多级标题(如 1.1、1.2.1)需要各级计数组合,用 counters(名, 连接符) 能把所有祖先的计数值用连接符串起来:

body { counter-reset: chapter; }   /* 章计数 */
h2 { counter-reset: section; }     /* 每个章内重置小节计数 */
h2::before {
    counter-increment: chapter;
    content: counter(chapter) " ";
}
h3::before {
    counter-increment: section;
    content: counters(section, ".") "  "; /* 读出祖先链,如 1.1 */
}

效果:h2 显示“1”“2”,其下的 h3 显示“1.1”“1.2”;h2 换章时小节自动从 .1 重新开始,长文档目录不再手工维护。

小结

计数器用 counter-reset 清零、counter-increment 累加、content 显示;嵌套层级交给 counters() 拼接。它把“编号”这类琐事交给 CSS,HTML 结构始终保持干净。

笔记加载中…