Grokking CSS Counters

Aniket Kudale
Level Up Coding
Published in
3 min readMar 10, 2020

--

Photo by Glenn Carstens-Peters on Unsplash

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, an <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 sections 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. The 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 — Insert 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 the 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 the 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 <counter value> —” to the beginning of each <h1> element.

CSS

HTML

Output

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 <value of the chapter counter>.”, and the “section” counter will be counted for each <h3> element with “<value of the chapter counter>.<value of the section counter>”

CSS

HTML

Output

CSS Counter are supported almost by all modern browsers.

I hope you liked this refresher on CSS Counters.

- Aniket Kudale

--

--