CSS counters

CSS counters are set through a variable, and the variable is incremented according to rules.


Using counters to automatically number

CSS counters increment a variable according to rules.

CSS counters use the following properties:

  • counter-reset- Create or reset counters
  • counter-increment- Incrementing variables
  • content- Insert generated content
  • counter()orcounters()Function - adds the counter's value to an element

To use CSS counters, you first need to create them with counter-reset:

The following example creates a counter on the page (in the body selector). Each <h2> element's counter value is incremented, and "Section <" is added before each <h2> element.counter value>:"

CSS Examples

body { counter-reset: section; } h2::before { counter-increment: section; content: "Section " counter(section) ": "; }

Try it Yourself »

nested counters

The following example creates a counter on the page, adding the counter value "Section <" before each <h1> element.Main heading counter value>.", the nested counter value is placed before the <h2> element, with the content "<"Main heading counter value>.<Subheading counter value>":

CSS Examples

body { counter-reset: section; } h1 { counter-reset: subsection; } h1::before { counter-increment: section; content: "Section " counter(section) ". "; } h2::before { counter-increment: subsection; content: counter(section) "." counter(subsection) " "; }

Try it Yourself »

Counters can also be used in lists, where child elements of the list are created automatically. Here we usecounters()Function to insert strings at different nesting levels:

CSS Examples

ol { counter-reset: section; list-style-type: none; } li::before { counter-increment: section; content: counters(section,".") " "; }

Try it Yourself »

CSS Counter Properties

Property Description
content Use the ::before and ::after pseudo-elements to insert automatically generated content
counter-increment Increment one or more values
counter-reset Create or reset one or more counters
other extensions