gpt4 book ai didi

html - CSS 计数器在 div 内的子项中不起作用

转载 作者:行者123 更新时间:2023-12-03 17:01:21 25 4
gpt4 key购买 nike

我正在尝试使用 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>

最佳答案

这里的错误来自规则:

.itemsContainer {
counter-reset: section;
}

所以每次你有一个 .itemsContainer元素计数器 section将被重置。

为了避免这种情况只说只有 第一 .itemsContainer元素重置计数器:

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

对于“内部 div”部分,您需要增加 subsection使用 .item而不是 .item .t2 .不要忘记第一个元素不必增加计数器。在 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

关于html - CSS 计数器在 div 内的子项中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60225907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com