The CSS counter in my example doesn't increment although I have specified it to do so. I've read some questions here regarding the nesting level of the elements that can cause this but in my case, all the elements are in the same level.
The MWE
<!DOCTYPE html>
<head>
<style>
body {
counter-reset: firstCounter;
counter-reset: secondCounter;
}
h2.heading::before {
counter-increment: firstCounter;
content: counter(firstCounter)"\00a0";
}
h3.issue::before {
counter-increment: secondCounter;
content: counter(secondCounter)"\00a0";
}
</style>
</head>
<body>
<h1>The Book</h1>
<h2 class="heading">First Heading</h2>
<h3 class="issue">The Issue of Drinking</h3>
<h3 class="issue">The Issue of Drinking Too Much</h3>
<h2 class="heading">Second Heading</h2>
<h3 class="issue">The Issue of Driving</h3>
<h3 class="issue">The Issue of Drunk Driving</h3>
</body>
</html>
Result
The counter for the heading “Second Heading,” needs to be “2.” Swapping the order of counter-reset
under the body
tag in the CSS causes the same problem but inversed with regard to which heading is affected.
The problem is the repeated definition of the counter-reset
property:
body {
counter-reset: firstCounter;
counter-reset: secondCounter;
}
The second definition overrides the first; to reset multiple counters you simply have to use a white-space separated list of those counters:
body {
counter-reset: firstCounter secondCounter;
}
Name: counter-reset
Value: [ ? ]+ | none
<custom-ident> <integer>?
The element alters the value of one or more counters on it. If there is not currently a counter of the given name on the element, the element creates a new counter of the given name with a starting value of 0 (though it may then immediately set or increment that value to something different).
body {
counter-reset: firstCounter secondCounter;
}
h2.heading::before {
counter-increment: firstCounter;
content: counter(firstCounter)"\00a0";
}
h3.issue::before {
counter-increment: secondCounter;
content: counter(secondCounter)"\00a0";
}
/* irrelevant, just for the sake of easier visuals in the answer: */
h2 {
border-top: 2px solid #aaa;
}
h3 {
margin-left: 2em;
}
<h1>The Book</h1>
<h2 class="heading">First Heading</h2>
<h3 class="issue">The Issue of Drinking</h3>
<h3 class="issue">The Issue of Drinking Too Much</h3>
<h2 class="heading">Second Heading</h2>
<h3 class="issue">The Issue of Driving</h3>
<h3 class="issue">The Issue of Drunk Driving</h3>
Reference: