CSS Counters

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.

CSS Counters-properties

CSS counter is a type of a variable that modifies the look of the content according to where it is located on the page. CSS checks how may times a particular counter has been used by incrementing it.

There are three main properties you can use to work with counters – CSS content, CSS counter increment and CSS counter reset:

PropertyDescription
contentCan be used along with ::before and ::after pseudo-elements to insert generated content
counter-incrementIncreases the value of the CSS counter by one or more, allowing you to keep track of it
counter-resetAllows you to create or reset CSS counters

CSS Counters- Displaying

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).

CSS Counters-automatic numbering

To use a CSS counter, it must first be created with counter-reset.

The following example creates a counter for the page (in the body selector), then increments the counter value for each <h2> element and adds “Section <value of the counter>:” to the beginning of each <h2> element

body {
  counter-reset: section;
}

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

CSS Counters- Nesting

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

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) " ";
}