CSS Counters

Pizza

Hamburger

Hotdogs

CSS counters are "variables" maintained by CSS, whose values can be incremented through CSS rules (to track their usage count).

Counters allow you to adjust the appearance of a counter based on its position in the document content.

Automatically Numbered with Counters

CSS counters are like "variables". Variable values can be incremented through CSS rules (to track their usage count).

To use CSS counters, we will use the following properties:

  • counter-reset - create or reset counter
  • counter-increment - increment counter value
  • content - insert generated content
  • counter() or counters() function - add the counter value to the element

To use CSS counters, you must first use counter-reset Create it.

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

Example

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

Try It Yourself

Nested Counters

The following example creates a counter for the page (section) and a counter for each <h1> element (subsection).

"section" counter for each <h1> element, while writing "Section" and the value of the section counter, "subsection" counter for each <h2> element, while writing the value of the section counter and the value of the subsection counter:

Example

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 are also very useful for creating outline lists, as a new instance of the counter is automatically created in the child elements. Here, we use counters() The function inserts a string between counters of different nesting levels:

Example

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

Try It Yourself

CSS Counter Attributes

Attribute Description
content Used with ::before and ::after pseudo-elements to insert generated content.
counter-increment Increment the value of one or more counters.
counter-reset Create or reset one or more counters.