Search code examples
csscss-counter

Using CSS Counters


How can I count a element if each of them is nested in a sepereate element ?

    .variant--name::before {
      counter-increment: section;
      content: "Abschnitt " counter(section) ": ";
    }
<div class="variant--group">
<h3 class="variant--name">variant</h3>
</div>

<div class="variant--group">
<h3 class="variant--name">variant</h3>
</div>

<div class="variant--group">
<h3 class="variant--name">variant</h3>
</div>


Solution

  • You also need counter-reset

    body {
      counter-reset: section;
    }
    .variant--name::before {
      counter-increment: section;
      content: "Abschnitt " counter(section)": ";
    }
    <div class="variant--group">
      <h3 class="variant--name">variant</h3>
    </div>
    <div class="variant--group">
      <h3 class="variant--name">variant</h3>
    </div>
    <div class="variant--group">
      <h3 class="variant--name">variant</h3>
    </div>

    Edit: You can create parent element and use counter-reset on it, so now for every parent element you create new instance of counter Fiddle instead of resetting counter on body Fiddle