🎁 Checkout my Learn React by Making a Game course and get 1 month Free on 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:

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

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.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *