Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

How to use Counters in CSS

We know that in HTML there we have the ol - ordered lists. By default what they do is to add a counter in front of any element that is on the list.

For example, the below is an ordered list made with ol and li tags:

  1. Cats
  2. Lions
  3. Tigers
  4. Jaguars

Those numbers are added by using CSS Counters. And we can add this behavior to any element we want, not just ordered lists.

Take for example the following HTML code:

    <h4>The Cats</h4>
    It is the only domesticated species in the family.
    <h4>The Lions</h4>
    It is a muscular, deep-chested cat with a short, rounded head.
    <h4>The Jaguars</h4>
    This spotted cat closely resembles the leopard, but is usually larger and sturdier.

If we want to add numbers to all h4 of a section first we will need to set the name and the value to zero for a new counter:

body { counter-reset: sectionsCounter; }

Next for each section we see, we will want to increment the counter:

section {counter-increment: sectionsCounter;}

And finally, use the counter’s value as content for the :before of a h4:

h4: before { content: counter(sectionsCounter) ". "; }

And voila. Now we’ll have section headings like 1. The Cats and 2. The Lions and so on.

See the full example here.

Home Screencasts Best of Newsletter Search X