【问题标题】:CSS counters doesn't work in subitems inside of divCSS 计数器在 div 内的子项中不起作用
【发布时间】:2020-02-14 11:58:30
【问题描述】:

我正在尝试使用 CSS 计数器来创建章节编号。 正如您在下面的示例中所看到的,如果我处理容器内的类,它可以正常工作,但是当我尝试在 div 内的子项中使用它时它不起作用。知道如何纠正这种行为吗? (我需要使用这种结构)

.itemsContainer {
  counter-reset: section;
}

.t1 {
  counter-reset: subsection;
}

.t1:before {
  counter-increment: section;
  content: counter(section) ". ";
}

.t2:before {
  counter-increment: subsection;
  content: counter(section) "."counter(subsection) " ";
}
<h3>Direct access to class</h3>
<div class="itemsContainer">
  <p class="t1"></p>
  <p class="t2"></p>
  <p class="t2"></p>
</div>

<h3>Inside div</h3>
<div class="itemsContainer">
  <div class="item">
    <p class="t1"></p>
  </div>
  <div class="item">
    <p class="t2"></p>
  </div>
  <div class="item">
    <p class="t2"></p>
  </div>
</div>

【问题讨论】:

标签: html css css-counter


【解决方案1】:

这里的错误来自规则:

.itemsContainer {
  counter-reset: section;
}

因此,每当您有一个 .itemsContainer 元素时,计数器 section 就会被重置。

为了避免这种情况,只需说只有 first .itemsContainer 元素会重置计数器:

.itemsContainer:nth-of-type(1) {
  counter-reset: section;
}

对于“内部 div”部分,您需要使用 .item 而不是 .item .t2 递增 subsection。不要忘记第一个元素不必增加计数器。在 css 中,您可以使用 :not() 属性:

.item:not(:first-child) {
  counter-increment: subsection;
}

请查看演示:

.itemsContainer:nth-of-type(1) {
  counter-reset: section;
}

.itemsContainer .t1 {
  counter-reset: subsection;
}

.t1::before {
  counter-increment: section;
  content: counter(section) ". ";
}

.item:not(:first-child) {
  counter-increment: subsection;
}

.itemsContainer>.t2::before {
  counter-increment: subsection;
  content: counter(section) "."counter(subsection) " ";
}

.itemsContainer>.item>.t2::before {
  content: counter(section) "."counter(subsection) " ";
}
<h3>Direct access to class</h3>
<div class="itemsContainer">
  <p class="t1"></p>
  <p class="t2"></p>
  <p class="t2"></p>
</div>

<h3>Inside div</h3>
<div class="itemsContainer">
  <div class="item">
    <p class="t1"></p>
  </div>
  <div class="item">
    <p class="t2"></p>
  </div>
  <div class="item">
    <p class="t2"></p>
  </div>
</div>

更多详情请查看 W3C 文档:https://www.w3schools.com/CSS/css_counters.asp

【讨论】:

  • 在“Inside div”之后数字没有重置,这不是奇怪的行为吗?
  • @TmZn 你这是什么意思?
猜你喜欢
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 2017-01-07
相关资源
最近更新 更多