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

前端之家收集整理的这篇文章主要介绍了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>之前创建它元素,然后立即关闭…因此您不会在初始计数器上重置.

原文链接:https://www.f2er.com/html/224930.html

猜你在找的HTML相关文章