The following CSS counter example does not work as expected. The counter for sub-headings should reset after every main heading:
body {
font: smaller sans-serif;
counter-reset: h1 h2;
}
h1:before {
counter-reset: h2;
content: counter(h1) ". ";
counter-increment: h1;
}
h2:before {
content: counter(h1) "." counter(h2) ". ";
counter-increment: h2;
}
<h1>Heading</h1>
<h2>Sub-heading</h2>
<h2>Sub-heading</h2>
<h1>Heading</h1>
<h2>Sub-heading</h2>
<h2>Sub-heading</h2>
However, the following works as expected:
body {
font: smaller sans-serif;
counter-reset: h1 h2;
}
h1:before {
content: counter(h1) ". ";
counter-increment: h1;
}
h1 {
counter-reset: h2;
}
h2:before {
content: counter(h1) "." counter(h2) ". ";
counter-increment: h2;
}
<h1>Heading</h1>
<h2>Sub-heading</h2>
<h2>Sub-heading</h2>
<h1>Heading</h1>
<h2>Sub-heading</h2>
<h2>Sub-heading</h2>
My question is, why does counter-reset
not work inside pseudo elements?
I believe this is a scope problem. The docs state:
Counters are "self-nesting", in the sense that resetting a counter in a descendant element or pseudo-element automatically creates a new instance of the counter....
... The scope of a counter starts at the first element in the document that has a 'counter-reset' for that counter and includes the element's descendants and its following siblings with their descendants. However, it does not include any elements in the scope of a counter with the same name created by a 'counter-reset' on a later sibling of the element or by a later 'counter-reset' on the same element.
The way I understand this is that when you reset the counter a new instance of the counter is created on the parent element. If you do this on h1:before
it gets created on that single <h1>
element which is then immediately closed... hence you get no reset on the initial counter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With