CSS counters are used to add counts to elements. The count is added by providing variables that can be initialized (using counter-reset), and these variables can then be incremented by CSS rules.

Many developers overlook this powerful CSS feature, and that is why we are going to talk about how to work with counters in this tutorial.

When to Use CSS Counters

CSS counters can be used whenever you need a counting system on your web page. Some of the best use cases are:

  • Numbering complex lists
  • Create dynamic pagination links
  • Numbering steps in an on-boarding system.

In this tutorial, we will be talking about how to use CSS counters to make complex lists and create dynamic pagination.

How to Use CSS Counters

The CSS counting system consists of the counter-reset, counter-increment, counter() and counters() and content properties. These properties take care of everything you need to do in the CSS counting system.

Let’s look more closely at these properties so we understand how they can be used.

Counter Properties Explained

  • counter-reset: Used to reset or initialize your counter. To use CSS counters you must first create one with this property.
  • counter-increment: Used to increment the variable of an already initialized counter.
  • counter(): This function does the magic. It’s used inside the content property, on a :before or :after pseudo selector, to add up the counts.
  • counters(): Used for inherited counting, and generates the instance of a parent counter variable in the child.
  • content: Used to add up the count value (strings) by manipulating content for :before and :after CSS selectors.

Now that we understand these CSS counter properties and values, let’s dive in to our examples.

  1. Numbering elements on a web page
  2. Making dynamic pagination

Numbering Elements on a Web page

Numbering can be done in HTML, but CSS numbering provides dynamic and easy-to-control ways of doing the job using CSS counters. The following example will number the elements on web page with CSS.

Firstly, we are going to set up some simple numbering that does just one-level numbering. Then we’ll move on to a more advanced example where we’ll set up a table of contents.

Simple Numbering

In this example, we’ll create a simple items counter with CSS. In your HTML, just create your items structure like this:

<div>
  <p>Mercury</p>
  <p>Venus</p>
  <p>Earth</p>
</div>

In the CSS we are going to do three key things:

  1. Initialize the counter on the parent div using counter-reset
  2. Increment the counter value by 1 on the child div p using counter-increment
  3. Add the counter variables before the div p content using the :before pseudo selector.

Let’s go!

#css #web-development #developer

How to use CSS Counters to Automatically Number Elements
2.20 GEEK