I have a problem with CSS and counter. The second h3
should have the number "1.2" but in my case it has always the number "1.1".
Is this a problem with the divs around the h3 or did I make a mistake with the counter-reset? Thanks for your help! :)
I have the following 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>
The h2 that resets the h3counter is in a different container than the h3's. That means the h3counter will be in a different context than the h3's.
Solution: don't reset the counter in the h2, but in its parent .div, which is in the same container as the divs containing the h3's.
.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>
(Note: I had to translate the SCSS for this snippet, because snippet doesn't do SCSS, but you get the idea. All you need to replace is the first line of CSS I gave above.)