我的CSS和计数器有问题。第二个h3
应该具有数字“ 1.2”,但在我的情况下,它始终具有数字“ 1.1”。
这是h3周围的div的问题,还是我在计数器重置上犯了一个错误?谢谢你的帮助! :)
我有以下HTML:
body {
counter-reset: counterh2;
}
h2 {
counter-reset: counterh3;
}
h3 {
counter-reset: counterh4;
}
h4 {
counter-reset: counterh5;
}
.container {
>h2::before,
>.div>h2::before {
content: counter(counterh2, decimal) ". ";
counter-increment: counterh2;
}
>h3::before,
>.div>h3::before {
content: counter(counterh2, decimal) "." counter(counterh3, decimal) ". ";
counter-increment: counterh3;
}
>h4::before,
>.div>h4::before {
content: counter(counterh2, decimal) "." counter(counterh3, decimal) "." counter(counterh4, decimal) ". ";
counter-increment: counterh4;
}
>h5::before,
>.div>h5::before {
content: counter(counterh2, decimal) "." counter(counterh3, decimal) "." counter(counterh4, decimal) "." counter(counterh5, decimal) ". ";
counter-increment: counterh5;
}
}
<div class="container">
<div class="div">
<h2><span>Should be 1</span></h2>
</div>
<div class="div">
<h3><span>Should be 1.1</span></h3>
</div>
<div class="div">
<h3><span>Should be 1.2</span></h3>
</div>
</div>
最佳答案
重置h3counter的h2与h3位于不同的容器中。这意味着h3counter将与h3处于不同的上下文中。
解决方案:不要在h2中重置计数器,而在其父.div中重置该计数器,该父对象与包含h3的div位于同一容器中。
.container .div:first-child {
counter-reset: counterh3;
}
body {
counter-reset: counterh2;
}
.container .div:first-child {
counter-reset: counterh3;
}
h3 {
counter-reset: counterh4;
}
h4 {
counter-reset: counterh5;
}
.container>h2::before,
.container>.div>h2::before {
content: counter(counterh2, decimal) ". ";
counter-increment: counterh2;
}
.container>h3::before,
.container>.div>h3::before {
content: counter(counterh2, decimal) "." counter(counterh3, decimal) ". ";
counter-increment: counterh3;
}
.container>h4::before,
.container>.div>h4::before {
content: counter(counterh2, decimal) "." counter(counterh3, decimal) "." counter(counterh4, decimal) ". ";
counter-increment: counterh4;
}
.container>h5::before,
.container>.div>h5::before {
content: counter(counterh2, decimal) "." counter(counterh3, decimal) "." counter(counterh4, decimal) "." counter(counterh5, decimal) ". ";
counter-increment: counterh5;
}
<div class="container">
<div class="div">
<h2><span>Should be 1</span></h2>
</div>
<div class="div">
<h3><span>Should be 1.1</span></h3>
</div>
<div class="div">
<h3><span>Should be 1.2</span></h3>
</div>
</div>
(注意:我必须为此代码段翻译SCSS,因为代码段不执行SCSS,但是您明白了。您需要替换的是上面给出的CSS的第一行。)
关于html - 带嵌套div的SCSS计数器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48529874/