加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

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

发布时间:2020-12-14 18:52:01 所属栏目:资源 来源:网络整理
导读:以下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
以下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>之前创建它元素,然后立即关闭…因此您不会在初始计数器上重置.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读