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.
CSS counters can be used whenever you need a counting system on your web page. Some of the best use cases are:
In this tutorial, we will be talking about how to use CSS counters to make complex lists and create dynamic pagination.
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-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.
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.
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:
counter-reset
div p
using counter-increment
div p
content using the :before
pseudo selector.Let’s go!
#css #web-development #developer