How to Use CSS’s Counter-Reset Property

Published July 18, 2016 by CSS Newbies.

Most developers probably think of CSS as a means to bring designs to life, but CSS3 is capable of going beyond aesthetics. CSS3’s counter-reset property can actually be used to assign chronological numbers to certain sections and subsections of your HTML, which you can then use number certain elements. For this example, we’ll use the property to number the following code:

<h1>Section 1</h1>
<h2>Sub-Section of Section 1</h2>
<h2>Sub-Section of Section 1</h2>
<h1>Section 2</h1>

Screen Shot 2016-07-18 at 10.02.06 AM

To use it, the first thing you need to do is to define where/when the counter should be reset:

body{
counter-reset: section;
}

This resets the counter to start from zero. You can add any name as the value of the counter-reset property and it will work the same, just make sure you apply that name to the counter-increment property later on if you intent to use the property to automatically number your HTML elements.

To number the elements, we need to tell the CSS to increment them. Since we’re going to be numbering h1 elements, our CSS should look like this:

h1:before{
counter-increment: section;
content: counter(section)'. ';
}

In the above code, we’re basically telling the CSS to start incrementing the section counter for all the h1 elements. So the first h1 element will be automatically numbered 1, the second will be 2, and so on. To apply these numbers to their corresponding elements, we use the content property with the value ‘counter(section)’, so the value should always be counter + the name you assigned to the initial counter-reset property in your CSS (in parentheses!).

In the example we’re working with, we also decided to use subsections (the h2 elements), which can be numbered similarly. First, you’ll need to start a new counter for the subsections:

h1{
counter-reset: subsection;
}

To number them, the code is pretty much the same as numbering the h1 elements:

h2:before{
counter-increment: subsection;
content: counter(section)'.' counter(subsection)'- ';
}

Your final product should look something like this:

Screen Shot 2016-07-18 at 10.02.18 AM

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>