伪元素不能递增计数器,必须在真实元素上用counter-increment触发,再通过counter()或counters()在::before/::after中显示;多级编号需用counters(name, ".")拼接路径。
很多人尝试在 ::before 或 ::after 里写 counter-increment: item; 并期望它自动累加并显示,这是行不通的。伪元素只是「内容插入点」,计数器的递增必须发生在**真实元素上**(比如 、),而显示才可交给伪元素。
counter-increment,再用 counter() 在伪元素中显示标准流程分两步:声明计数器作用域 → 对每个匹配元素递增 → 在伪元素中调用显示。常见错误是把 counter-increment 写在伪元素选择器里,这不会生效。
counter-reset 通常放在父容器(如 ol、.list)上初始化计数器counter-increment 必须写在要“触发计数”的**实际 HTML 元素**的选择器里(例如 li、section)content: counter(item) 才能放在 ::before 或 ::after 中渲染数字body {
counter-reset: section;
}
section {
counter-increment: section;
}
section::before {
content: "第 " counter(section) " 节:";
font-weight: bold;
}
counter(section, decimal) 和 counters()
当需要类似「2.3.1」这样的层级编号时,counter() 只能取最内层值,必须改用 counters() —— 它会按作用域栈拼接所有同名计数器,用指定分隔符连接。
counter(section) → 输出当前层级数字(如 3)counters(section, ".") → 输出完整路径(如 "1.2.3")counter-increment,且父级 counter-reset 不影响子级作用域.chapter {
counter-reset: subsection;
}
.chapter h2 {
counter-increment: chapter;
}
.chapter h2::before {
content: counter(chapter) ". ";
}
.chapter h3 {
counter-increment: subsection;
}
.chapter h3::before {
content: counters(chapter, ".") "." counter(subsection) " ";
}
content 的字符串拼接与格式控制content 值是字符串拼接表达式,不是模板语法。空格、标点、单位都要显式写出;数字样式(如大写罗马数字)靠第二个参数控制,但不能加 CSS 样
式(如 text-transform)到伪元素数字部分上。
decimal、lower-roman、upper-alpha 等,写在 counter(name, style) 第二个参数counter() 返回值单独设置颜色或字体大小——整个伪元素需统一设置01),CSS 无原生支持,得靠 JS 或预设类名ol {
counter-reset: step;
}
.step-item {
counter-increment: step;
}
.step-item::before {
content: "步骤 " counter(step, upper-alpha) ":";
color: #2c3e50;
}
CSS 计数器和伪元素配合的关键,在于理解「递增动作必须绑定到真实 DOM 元素」这一约束。一旦把 counter-increment 放错位置,后续怎么调 counter() 都不会变。层级复杂时,counters() 的括号嵌套和分隔符容易漏写,建议先用简单结构验证再叠加。