Search code examples
csscss-counter

Repeated series of number via CSS


I'm trying to do something like this:

<h2>1.1 Bananas</h2>
<h3>1.1.1 </h3>
<h3>1.1.2 </h3>
<h3>1.1.3 </h3>

<h2>1.1 Apples</h2>
<h3>1.1.1 </h3>
<h3>1.1.2 </h3>
<h3>1.1.3 </h3>

<h2>1.1 Oranges</h2>
<h3>1.1.1</h3>
<h3>1.1.2</h3>
<h3>1.1.3</h3>

Notice how the number series repeats.

I can do autonumbering via CSS - but I can't figure out if there's a way to repeat the numbered series.


Solution

  • One way would to be use CSS counters and reset them every time a h2 is encountered like in below snippet.

    The counter-reset property within the h2 selector sets the value of the h2 counter to 1 and that of the h3 counter to 0 (default) everytime a h2 element is encountered.

    The counter-increment property within the h3 selector increments the value of the h3 counter everytime a h3 element is encountered.

    h2 {
      counter-reset: h2 1 h3 0;
    }
    h2:before {
      content: "1." counter(h2);
    }
    h3 {
      counter-increment: h3;
    }
    h3:before {
      content: "1." counter(h2)"." counter(h3);
    }
    <h2>Bananas</h2> <!-- h2 counter = 1, h3 counter = 0 -->
    <h3></h3> <!-- h2 counter = 1, h3 counter = 1 (increment) -->
    <h3></h3> <!-- h2 counter = 1, h3 counter = 2 (increment) -->
    <h3></h3> <!-- h2 counter = 1, h3 counter = 3 (increment) -->
    <h2>Apples</h2> <!-- h2 counter = 1 (reset), h3 counter = 0 (reset) -->
    <h3></h3> <!-- h2 counter = 1, h3 counter = 1 (increment) -->
    <h3></h3> <!-- h2 counter = 1, h3 counter = 2 (increment) -->
    <h3></h3> <!-- h2 counter = 1, h3 counter = 3 (increment) -->
    <h2>Oranges</h2> <!-- h2 counter = 1 (reset), h3 counter = 0 (reset) -->
    <h3></h3> <!-- h2 counter = 1, h3 counter = 1 (increment) -->
    <h3></h3> <!-- h2 counter = 1, h3 counter = 2 (increment) -->
    <h3></h3> <!-- h2 counter = 1, h3 counter = 3 (increment) -->


    Actually, you don't even need the h2 counter for your case because the value is always 1. So even the below in CSS would suffice:

    h2 {
      counter-reset: h3 0;
    }
    h2:before {
      content: "1.1";
    }
    h3 {
      counter-increment: h3;
    }
    h3:before {
      content: "1.1." counter(h3);
    }