counter-reset 必须设在计数父容器上而非子元素,如为编号需在其父级设counter-reset;counter-increment写在触发计数的元素上,按DOM顺序执行;多级编号用counters()配合统一计数器名和嵌套结构。

counter-reset 该在哪个元素上设置
必须放在要启动计数的父容器上,不是放在要显示编号的子元素上。比如给所有 <section></section> 自动编号,就得在它的直接父级(如 <main></main> 或 <article></article>)设 counter-reset: section-counter;如果错放在 <section></section> 自己身上,每个 <section></section> 都会重置为 0,结果全是「1」。
常见错误场景:
- 把
counter-reset写在<h2></h2>上,指望它给章节编号 → 实际只影响后续同级兄弟元素,且每次都会重置 - 用
display: none隐藏了某个<section></section>,但它仍参与计数 →counter-increment是基于 DOM 结构触发的,和可见性无关 - 嵌套结构中想分层编号(如 1.1、1.2),却只用一个 counter → 需要多个独立的
counter-reset和counter-increment配合
counter-increment 触发时机与作用对象
counter-increment 必须写在「要让计数器加 1」的那个元素上,而且是在渲染时按 DOM 顺序逐个执行的。它不关心元素是否显示、是否有内容,只要出现在文档流中(哪怕 visibility: hidden),就会触发自增。
典型用法:
- 给每个
<section></section>加编号:在<section></section>元素上写counter-increment: section-counter - 跳过某项不计数:不写
counter-increment,或用counter-increment: section-counter 0(等价于不加) - 一次加多:如
counter-increment: section-counter 2,会让计数器+2 - 多个计数器同时操作:
counter-increment: section-counter subsection-counter
counter() 函数怎么拼出层级编号(如 2.1.3)
counter() 只能取单个计数器当前值,要拼接多级编号得用 counters() —— 注意是复数形式。它会自动按嵌套深度把同一名称的计数器用指定字符串连接起来。
例如:
将 Markdown 文章转换为微信公众号兼容的纯 HTML 格式。当用户要求"转成微信格式"、"生成公众号文章 HTML"、"排版到微信草稿箱"、"微信粘贴格式"时触发。输出带内联样式的纯 HTML,微信编辑器可直接渲染,无需额外适配。支持标题、段落、列表、粗体、行内代码、表格、引用块、代码块、配图的完整转换。
section { counter-increment: section; }
subsection { counter-increment: subsection; }
section::before { content: counter(section) ". "; }
subsection::before { content: counters(section, ".") "." counters(subsection, ".") " "; }
但这样会出错:因为 counters() 默认只找同名计数器,而这里用了两个不同名(section 和 subsection)。正确做法是统一用一个名字,靠嵌套关系区分层级:
- 外层
<section></section>设counter-reset: chapter,并counter-increment: chapter - 内层
<subsection></subsection>不重置,只counter-increment: section,并在其上用counters(chapter, ".") - 关键点:
counters()的第二个参数是分隔符,第三个可选参数指定计数样式(decimal、lower-roman等)
浏览器兼容性与 display: contents 的坑
counter-reset 和 counter-increment 在所有现代浏览器中都稳定支持(包括 IE8+),但有个隐蔽问题:当父容器用了 display: contents,它会让子元素「视觉上提升一级」,但计数器仍按原始 DOM 层级计算,导致编号错乱。
比如:
<div style="display: contents"> <h2>标题</h2> <p>内容</p> </div>
此时 <h2></h2> 的 counter-increment 会和上层同级元素竞争,而不是严格属于这个 <div> 的上下文。解决办法只有两个:<ul>
<li>避免对含计数逻辑的容器使用 <code>display: contents
flex 或 grid 布局替代,保持 DOM 层级清晰另外,counter() 不能用于伪元素以外的 content(比如不能直接写在 div 的 content 样式里),也不支持在 JS 中读取值 —— 它纯属 CSS 渲染时的计算,没有对应 DOM 接口。










