Can someone help me understand what's happening with the following? I expect the <li> numbering to match the <h2> numbering, but it doesn't. Why not?
body {counter-reset: my-sec-counter; /* Set "my-sec-counter" to 0 */}.largesection {counter-reset: my-sec-counter;}li {counter-increment: my-sec-counter; /* Increment "my-sec-counter" by 1 */ }h2::before {content: "Section " counter(my-sec-counter) ". ";}
<div class="largesection"><ol><li><h2>HTML Tutorial</h2></li><li><h2>CSS Tutorial</h2></li></ol></div><div><ol><li><h2>Bootstrap Tutorial</h2></li><li><h2>SQL Tutorial</h2></li></ol></div><div class="largesection"><ol><li><h2>React Tutorial</h2></li><li><h2>Vue Tutorial</h2></li></ol></div>
I expect the result to be:
1. Section 1. HTML Tutorial2. Section 2. CSS Tutorial3. Section 3. Bootstrap Tutorial4. Section 4. SQL Tutorial1. Section 1. React Tutorial2. Section 2. Vue Tutorial
But instead, it's
1. Section 1. HTML Tutorial2. Section 2. CSS Tutorial1. Section 3. Bootstrap Tutorial //The li counter resets here but the h2 counter doesn't2. Section 4. SQL Tutorial1. Section 1. React Tutorial2. Section 2. Vue Tutorial
Best Answer
- ol counter doesn't use your custom counter.
- remove the reset in body. It's not necessary and may cause unspecified effects.
See this
.largesection {counter-reset: my-sec-counter;}ol {list-style: none;}li {/* Increment "my-sec-counter" by 1 */counter-increment: my-sec-counter;}h2::before { content: counter(my-sec-counter) ". Section " counter(my-sec-counter) ". ";}
<div class="largesection"><ol><li><h2>HTML Tutorial</h2></li><li><h2>CSS Tutorial</h2></li></ol></div><div><ol><li><h2>Bootstrap Tutorial</h2></li><li><h2>SQL Tutorial</h2></li></ol></div><div class="largesection"><ol><li><h2>React Tutorial</h2></li><li><h2>Vue Tutorial</h2></li></ol></div>
If you want to use the inner ol counter instead of overriding it, you can use the ol start="3" html attribute on the second ol. This is valid HTML because numbering a list isn't just for styling purposes. In fact, this is the recommended way for screen readers and crawlers.