html – CSS计数器重置在伪元素内不起作用

以下CSS计数器示例无法正常运行.每个主要标题后,应重新设置子标题的计数器:
body {
  font: smaller sans-serif;
  counter-reset: h1 h2;
}
h1:before {
  counter-reset: h2;
  content: counter(h1) ". ";
  counter-increment: h1;
}
h2:before {
  content: counter(h1) "." counter(h2) ". ";
  counter-increment: h2;
}
<h1>heading</h1>
<h2>Sub-heading</h2>
<h2>Sub-heading</h2>
<h1>heading</h1>
<h2>Sub-heading</h2>
<h2>Sub-heading</h2>

但是,以下工作如预期的那样:

body {
  font: smaller sans-serif;
  counter-reset: h1 h2;
}
h1:before {
  content: counter(h1) ". ";
  counter-increment: h1;
}
h1 {
  counter-reset: h2;
}
h2:before {
  content: counter(h1) "." counter(h2) ". ";
  counter-increment: h2;
}
<h1>heading</h1>
<h2>Sub-heading</h2>
<h2>Sub-heading</h2>
<h1>heading</h1>
<h2>Sub-heading</h2>
<h2>Sub-heading</h2>

我的问题是,为什么反重置在伪元素内不起作用?

解决方法

我相信这是范围问题. docs状态:

Counters are “self-nesting”,in the sense that resetting a counter in
a descendant element or pseudo-element automatically creates a new
instance of the counter….

… The scope of a counter starts at the first element in the document
that has a ‘counter-reset’ for that counter and includes the element’s
descendants and its following siblings with their descendants.
However,it does not include any elements in the scope of a counter
with the same name created by a ‘counter-reset’ on a later sibling of
the element or by a later ‘counter-reset’ on the same element.

我理解的方式是,当您重置计数器时,会在父元素上创建计数器的新实例.如果您在h1上执行此操作:在单个< h1>之前创建它元素,然后立即关闭…因此您不会在初始计数器上重置.

相关文章

Mip是什么意思以及作用有哪些
怎么测试Mip页面运行情况
MIP安装的具体步骤有哪些
HTML添加超链接、锚点的方法及作用详解(附视频)
MIP的规则有哪些
Mip轮播图组件中的重要属性讲解