counter-reset 与 counter-increment 是 css 计数器机制的配对核心:前者声明并初始化计数器(如 counter-reset: section;),后者在匹配元素上触发递增(如 counter-increment: section;);二者名称必须严格一致,且 counter-reset 必须作用于父容器才能使子元素的 counter-increment 有效。

counter-reset 和 counter-increment 是什么关系
它们是 CSS 计数器机制的两个基础属性,counter-reset 用来「声明并初始化」一个计数器(比如设为 0),counter-increment 用来「每次匹配到元素时给它加 1」。没有 counter-reset,counter-increment 就会报无效——浏览器根本不知道这个计数器从哪来。
常见误区是以为只要写 counter-increment: section; 就能自动编号,结果发现没反应。原因几乎总是漏了 counter-reset,或者它没作用在合适的父容器上。
怎么让 h2 标题自动编号(如 1.、2.、3.)
关键不是给 h2 自己设 counter-reset,而是给它的**最近公共父容器**(比如 article 或 body)设 counter-reset: section;,再让每个 h2 执行 counter-increment: section;,最后用 content: counter(section) ". " 插入编号。
-
counter-reset: section;写在article上,表示“在这个 article 里,section 计数器从 0 开始” -
h2 { counter-increment: section; }表示“每遇到一个 h2,section 加 1” -
h2::before { content: counter(section) ". "; }把当前值拼成前缀
如果页面有多个 article,每个都会独立计数,互不影响——这是 counter-reset 作用域决定的。
嵌套编号(如 1.1、1.2、2.1)怎么写
靠多级计数器 + counter() 的第二个参数。比如 h2 用 section,h3 用 subsection,并在 h3 的 counter-reset 中绑定上级: counter-reset: subsection; 放在 h2 上,而不是全局。
这样每个 h2 都会重置自己的 subsection,h3 每次只在对应 h2 下累加。显示时用 counter(section) 和 counter(subsection) 拼接,或直接用 counters(subsection, ".") 自动生成带点分隔的嵌套格式。
h2 { counter-increment: section; counter-reset: subsection; }h3 { counter-increment: subsection; }h3::before { content: counter(section) "." counter(subsection) " "; }
注意:counters() 第二个参数必须是字符串字面量,比如 ".",不能是变量或 CSS 变量,否则不生效。
为什么编号没更新或重复了
最常踩的坑是 DOM 结构和 CSS 选择器没对齐。比如把 counter-reset 写在 div.content 上,但实际 h2 在 div.content > section > h2 里,而中间的 section 没有继承或重置行为,就可能打断计数流。
- 检查浏览器开发者工具的「Computed」面板,确认目标元素是否真的计算出了
counter-increment值 -
counter-reset的值如果是none或未声明,子元素的counter-increment会被忽略 - 用
display: none隐藏的元素仍参与计数;用visibility: hidden则照常计数 - 动态插入的元素(JS 添加)需要确保其父容器已有
counter-reset,否则新元素不会触发初始计数
计数器是纯 CSS 运行时行为,不依赖 JS,但也不感知 DOM 变化事件——它只按渲染树顺序逐个应用规则。结构一乱,编号就容易错位。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











