Skip to content

CSS 计数器

CSS 计数器可以在不写死数字的情况下,用 counter-resetcounter-incrementcounter() / counters()::before::after 里显示自动递增的编号,适合列表、章节、步骤等。

三个要点

  1. counter-reset:在某个祖先上「创建并重置」计数器,可指定名字和初始值。
  2. counter-increment:在需要计数的元素上「递增」该计数器。
  3. counter(名字)counters(名字, 分隔符):在 content 里输出当前计数值(常用于 ::before / ::after)。

基本示例:给标题自动编号

css
.section {
  counter-reset: section;  /* 计数器名为 section,从 0 开始 */
}

.section h2 {
  counter-increment: section;
}

.section h2::before {
  content: counter(section) ". ";
}

每个 h2 前会显示 "1. "、"2. "、"3. " …


多级编号(如 1.1、1.2、2.1)

嵌套的计数器:父级用 counter-reset 创建子计数器,子元素 counter-increment 并可用 counters() 输出「父.子」:

css
.section {
  counter-reset: section;
}

.section h2 {
  counter-increment: section;
  counter-reset: subsection;  /* 每个 h2 下重置 subsection */
}

.section h2::before {
  content: counter(section) ". ";
}

.section h3 {
  counter-increment: subsection;
}

.section h3::before {
  content: counter(section) "." counter(subsection) " ";
}

可得 "1.1 "、"1.2 "、"2.1 " 等。若用 counters(section, ".") 可自动带出多级路径(需在对应层级 increment 和 reset)。


指定初始值或步长

css
.section {
  counter-reset: section 5;  /* 从 5 开始 */
}

.section h2 {
  counter-increment: section 2;  /* 每次 +2 */
}

小结

  • counter-reset:在祖先上创建/重置计数器。
  • counter-increment:在要计数的元素上递增。
  • content: counter(名字)counters(名字, ".") 在 ::before/::after 里显示编号。
  • 适合列表编号、章节号、步骤号等,无需在 HTML 里写数字。

下一节学习 CSS 网页布局