Z
ZHANK
现代布局

CSS 计数器

counter-reset/counter-increment、嵌套计数器、自动编号

CSS 计数器

CSS 计数器自动为元素编号——章节标题、有序列表、图表标注。

学完本章你将: 掌握 counter-reset/counter-increment、嵌套计数器。


基本用法

css
/* 初始化计数器 */
body { counter-reset: section; }

/* 每个 h2 自增并显示编号 */
h2::before {
  counter-increment: section;
  content: "第 " counter(section) " 章 ";
}

嵌套计数器

css
body { counter-reset: chapter; }
h2 {
  counter-reset: section;         /* 每个章节重置小节编号 */
}
h2::before {
  counter-increment: chapter;
  content: counter(chapter) ". ";
}
h3::before {
  counter-increment: section;
  content: counter(chapter) "." counter(section) " ";
}

自定义编号样式

css
/* 罗马数字 */
h2::before {
  counter-increment: chapter;
  content: counter(chapter, upper-roman) ". ";
  /* decimal / upper-roman / lower-alpha / upper-alpha 等 */
}

有序列表替代

css
ol { counter-reset: item; list-style: none; }
li::before {
  counter-increment: item;
  content: counters(item, ".") " ";    /* counters(复数) */
}