Creating Automatic Numbering with CSS Counter

04 / Apr / 2016 by Amit Narayan 0 comments

As you know, in front end development when we add lists to the <ol> element, a numbered list gets generated automatically.

Similarly, we can generate numbers for any element using CSS Counter. Let’s see how it is done?

Usage:

CSS Counter has two main properties: “counter-reset” and “counter-increment”.

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

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

Here is the image that shows the number of <h1>.

img1

In case you want the number to start from specific number, you can specify the “reset number” as follows:

body {
    counter-reset: number 1;
}

If the reset number is not declared clearly it will be set it as 0 as default, and the count will start from 1.

Similarly, the numbering will start from the next number to the one in the counter-reset property. So, as per given example code above, the count will start from 2.

Here is the image that show the number of <h1> starting from 2.

img2

Even, 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) ". ";
}

Here is the image that shows the roman number of <h1>.

img3

FOUND THIS USEFUL? SHARE IT

Leave a comment -