DEV Community

Aniket Kudale
Aniket Kudale

Posted on

Understanding CSS Counters

CSS Counters are basically variables whose values can be used to number the content based on its placement in the web document. Generally in HTML, <ol> tag is used to give ordered numbers to the items of the list, but CSS counter allows us to do the same thing but in a different way. For example, you can use CSS counter to automatically number the headings or section in a web page. The values of the CSS counters can be incremented by CSS rules, which helps in tracking how many times the rules are used.

CSS counters uses the following properties:

  • counter-reset— Creates or resets a CSS counter. To use a counter, it must be first initialized to a value with this property. This value is 0 by default. Same property can be used to changes its value to any specific number.

  • counter-value — Once initialized, a counter’s value can be increased with this property.

  • content — Inserts generated content.

  • counter() or counters() function — Adds value of the counter to the element. The value of the counter can be displayed using either the counter() or counters() function in content property.

The counter() function has two forms: ‘counter(name)’ or ‘counter(name, style)’. The generated text is the value of the innermost counter of the given name in scope at the given pseudo-element. It is formatted in the specified style given as parameter to counter() function (decimal by default).

The counters() function also has two forms: ‘counters(name, string)’ or ‘counters(name, string, style)’. The generated text is the value of all counters with the given name in scope at the given pseudo-element, from outermost to innermost, separated by the specified string. The counters are rendered in the indicated style given as parameter to counter() function (decimal by default).

To use a CSS counter, it must be created with counter-reset. The counter’s name cannot be “none”, “inherit” or “initial”. If it is so, it will be ignored.

Let’s check an example:

Basic Counters

The following example creates a counter for entire page (since we have created a counter for chapter in body selector), then we increment the counter value for each <h1> element and text “Chapter — “ to the beginning of each <h1> element.

CSS

HTML

Output

See the Pen Basic Counters by Aniket Kudale (@aneeket) on CodePen.

Nested Counters

The following example creates one counter for the page (chapter) and one counter for each <h1> element (section) The “chapter” counter will be counted for each <h1> element with “Section .”, and the “section” counter will be counted for each <h3> element with “.”

CSS

HTML

Output

See the Pen Nested Counters by Aniket Kudale (@aneeket) on CodePen.

CSS Counter are supported almost by all modern browsers.

https://caniuse.com/#search=counters

I hope you liked this refresher on CSS Counters.

Top comments (0)