CSS counters don't work inside other elements

423 views Asked by At

This problem is not a duplicated of CSS counter-increment is not working for nested div and h3 elements

I have a problem using CSS counters when the element on which is applied is inside other elements:

HTML:

<div>
    <div>
        <h1>HTML/CSS Tutorials</h1>
    </div>
</div>
<div>
    <div>
        <h2>HTML</h2>
    </div>
</div>
<div>
    <div>
        <h2>CSS</h2>
    </div>
</div>
<div>
    <div>
        <h2>Bootstrap</h2>
    </div>
</div>


<h1>Scripting Tutorials</h1>
<h2>JavaScript</h2>
<h2>jQuery</h2>
<h2>React</h2>

CSS:

body {
  counter-reset: section;
}

h1 {
  counter-reset: subsection;
}

h1::before {
  counter-increment: section;
  content: "Section " counter(section) ". ";
}

h2::before {
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}

For the second section it's working fine, but for the first one, the subsection keeps reseting and it's always showing 1. Please advise, thanks!

enter image description here

1

There are 1 answers

0
Lisa On

If you add a class to the h1 parent div, you can do it this way:

h1::before, h2::before {
    color: red;
}
div.heading {
    counter-increment: item;
    counter-reset: item2;
}
div.heading + div {
    counter-increment: item2;
}

div ~ div {
    counter-increment: item2;
}

h1::before {
    content: "Section " counter(item) ". ";
}

h2::before {
    content: counter(item) "." counter(item2) " ";
}
<div class="heading">
    <div>
        <h1>HTML/CSS Tutorials</h1>
    </div>
</div>
<div>
    <div>
        <h2>HTML</h2>
    </div>
</div>
<div>
    <div>
        <h2>CSS</h2>
    </div>
</div>
<div>
    <div>
        <h2>Bootstrap</h2>
    </div>
</div>

<div class="heading">
    <div>
        <h1>HTML/CSS Tutorials</h1>
    </div>
</div>
<div>
    <div>
        <h2>HTML</h2>
    </div>
</div>
<div>
    <div>
        <h2>CSS</h2>
    </div>
</div>
<div>
    <div>
        <h2>Bootstrap</h2>
    </div>
</div>