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 *

Home Screencasts Best of Newsletter Search X

๐Ÿ“– 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X