In my quest to automatically number headings with multiple levels of hierarchy in an HTML document using CSS, I have encountered various examples online that heavily rely on counter-reset. However, despite testing it in different configurations, I haven't been able to make it work effectively.
I specifically need the h3 counter (subsection) to reset at each new h2 heading.
Here's a simple example code snippet to illustrate:
body {
counter-reset: section subsection;
}
.countheads>h2::before {
counter-increment: section;
content: counter(section, upper-roman);
counter-reset: subsection;
}
.countheads>h3::before {
counter-increment: subsection;
content: counter(section, upper-roman) "." counter(subsection);
}
<body>
<div class="countheads">
<h1>
Main title
</h1>
<h2>
Wuhhh
</h2>
<h3>
First point
</h3>
<h3>
Second point
</h3>
<h3>
Third point
</h3>
<h2>
Whoa
</h2>
<h3>
First point
</h3>
<h3>
Second point
</h3>
<h3>
Third point
</h3>
</div>
</body>
The intended behavior is for subsections in section II to restart at 1, such as II.1, II.2.
To achieve this, changing the counter-reset statement to counter-set produces the desired outcome:
body {
counter-reset: section subsection;
}
.countheads > h2::before {
counter-increment: section;
content: counter(section, upper-roman);
counter-set: subsection;
}
.countheads > h3::before {
counter-increment: subsection;
content: counter(section, upper-roman) "." counter(subsection);
}
<body>
<div class="countheads">
<h1>
Main title
</h1>
<h2>
Wuhhh
</h2>
<h3>
First point
</h3>
<h3>
Second point
</h3>
<h3>
Third point
</h3>
<h2>
Whoa
</h2>
<h3>
First point
</h3>
<h3>
Second point
</h3>
<h3>
Third point
</h3>
</div>
</body>
Surprisingly, even though syntax highlighters may flag the counter-set statement as an error, it actually delivers the expected functionality. So why does counter-reset fail while counter-set succeeds in this scenario?