|

Using CSS counter() function

Using CSS counter() function Photo by Pankaj Patel on Unsplash

How to use the counter() function in CSS

CSS counters allow you to automatically display the quantity of specific elements on a page. You can use them to count the number of items in a list, for example. 📝

Counters are essentially variables maintained by CSS, which can be incremented or decremented using style rules like any other.


Using counters

The first thing you need to do is initialize the counter in a selector with the counter-reset property.

Then, the value can be incremented or decremented using the counter-increment property.

The current value of a counter can be displayed using the counter() or counters() function, usually with the help of a content pseudo-element.

div {
  counter-reset: mycounter; 
}

Once initialized, the counter’s value can be increased or decreased using counter-increment. With the following declaration, the mycounter variable will be incremented once for each p element.

p::before {
  counter-increment: mycounter;
}

Displaying the counter

Now, to use the counter as we defined earlier, we will use the counter() function within the content property.

p::before {
  counter-increment: mycounter;
  content: "#" counter(mycounter) ": ";
}

Then, with the following HTML structure:

<div>
  <p>Hello!</p>
  <p>How are you?</p>
  <p>Great, thank you!</p>
</div>

We will get the following result:

Hello!

How are you?

Great, thanks!


Nested counters

CSS counters can also number lists with multiple levels. Here’s an example of an ordered list where each parent item may or may not have child items. We will use the following HTML structure:

<section>
  <ol>
    <li>item</li>
    <li>
      item
      <ol>
        <li>item</li>
        <li>item</li>
        <li>item</li>  
      </ol>
    </li>
    <li>
      item
      <ol>
        <li>item</li>
      </ol>
    </li>
    <li>
      item
      <ol>
        <li>item
          <ol>
            <li>item</li>
            <li>item</li>
          </ol>
        </li>
        <li>item</li>
      </ol>
    </li>
    <li>item</li>
  </ol>
</section>

As ol elements usually have a predefined ordering, we need to include the following in our CSS:

ol {
  list-style-type: none;
}

And regarding counters, we’ll add:

ol {
  list-style-type: none;
  counter-reset: nestedcounter;
}
li::before {
  counter-increment: nestedcounter;
  content: counters(nestedcounter, ".") " ";
}

This will result in:

  1. item
  2. item
    1. item
    2. item
    3. item
  3. item
    1. item
  4. item
    1. item
      1. item
      2. item
    2. item
  5. item

I hope this article helps you implement CSS counters in your projects. If you have suggestions or questions, feel free to reach out. Until next time! 👋