Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS counter-reset does not work inside pseudo elements

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?

like image 611
Salman A Avatar asked Feb 26 '15 14:02

Salman A


1 Answers

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.

like image 56
pschueller Avatar answered Sep 19 '22 12:09

pschueller