CSS Counters

Ordered lists aren’t the only elements that can be automatically numbered. Thanks to the various counter-related properties, any element can be.

CSS counters let you adjust the appearance of content based on its location in a document. For example, you can use counters to automatically number the headings in a webpage. Counters are, in essence, variables maintained by CSS whose values may be incremented by CSS rules to track how many times they’re used.

Using counters

To use a CSS counter, it must first be initialized to a value with the counter-reset property (0 by default). The same property can also be used to change its value to any specific number. Once initialized, a counter’s value can be increased or decreased with counter-increment. The counter’s name must not be “none”, “inherit”, or “initial”; otherwise the declaration is ignored.

Displaying a counter

The value of a counter can be displayed using either the counter() or counters() function in a content property.

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

The counters() function also has two forms: ‘counters(namestring)’ or ‘counters(namestringstyle)’. 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 specified style (decimal by default).

Nesting counters

A CSS counter can be especially useful for making outlined lists, because a new instance of the counter is automatically created in child elements. Using the counters() function, separating text can be inserted between different levels of nested counters.

Scroll to top