Automatic Numbering with CSS Counter

We have covered a lot of cool CSS3 capabilities – from Color Gradients, Transitions, and Animation. Actually, there are also several properties in CSS2 that is really useful but less known, including one we are going to discuss in this post: CSS Counter.

As you may already know, when we add lists with the <ol> element, the list is numbered automatically. By using CSS Counter, we can even number any element. So, let’s see how it is done.

Basic Usage

CSS Counter consists of two main properties: counter-reset and counter-increment. The counter-reset is used to reset the count, while the counter-increment – coupled with pseudo-element – is used to add the numbers.

The following code is a basic example of how we number a <h1> element with these properties.

body {
counter-reset: number;
}
h1:before {
counter-increment: number;
content: "counter(number) ";
}

This code gives us the following result.

CSS counter simple numbering example

In case you want the number to start from specific point, you can specify the “reset number” this way.

body {
counter-reset: number 1;
}

This number that we added in the above code is the “reset number”. If it is not declared explicitly it will be set at 0 as the default, and the count will initialize from 1. In other words, the generated number will initialize from the next number of the one in the counter-reset property. So, given our example above, the count will start from 2.

CSS counter reset start example

Furthermore, you can also change the type of the number, which is specified within the content property.

h2:before {
counter-increment: first;
content: counter(number, upper-roman) ". ";
}

The result will turn out as follows.

CSS counter Roman numeral example

Final Thought

This property might only be useful for a particular type of website, and it is likely that you will not use it every day. But we hope this post can be a good reference for when you need it. And if you have any questions regarding the subject, feel free to post the question in the comment box below.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail