How to Use CSS’s Counter-Reset Property

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:

  1. <h1>Section 1</h1>
  2. <h2>Sub-Section of Section 1</h2>
  3. <h2>Sub-Section of Section 1</h2>
  4. <h1>Section 2</h1>

Screen Shot 2016-07-18 at 10.02.06 AM

Join us in our newest publication:

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

  1. body{
  2. counter-reset: section;
  3. }

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:

  1. h1:before{
  2. counter-increment: section;
  3. content: counter(section)'. ';
  4. }

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:

  1. h1{
  2. counter-reset: subsection;
  3. }

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

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

Your final product should look something like this:

Screen Shot 2016-07-18 at 10.02.18 AM

Share and Enjoy !

0 0