Skip to main content

CSS Counters

Headings, sections and list items can be numbered automatically by CSS counters, with no scripting involved.

Think of a counter as a variable maintained by CSS, whose value rules can increase or decrease.


CSS Automatic Numbering With Counters

Since counters behave like variables, CSS rules can change their values.

These are the properties involved:

  • counter-reset - Creates a counter or resets it
  • counter-increment - Raises or lowers a counter's value
  • content - Inserts generated content
  • counter() - Puts a counter's value into an element

A counter does not exist until counter-reset creates it, so that step always comes first.


CSS Increase and Decrease Counter

In this example the body selector creates a page-wide counter, and each <h2> element then raises its value by 1.

Example

Prompt
Create a page that uses CSS counters to automatically number h2 headings. Use counter-reset on the body to create a counter called "section", then use counter-increment and content on h2::before to display "Section X: " before each heading. Include three h2 elements with some paragraph text.
Output: complete HTML page

Decrementing a Counter

A second parameter on counter-increment sets the step, which defaults to 1. Making it -1 decreases the counter value.

Example

Prompt
Create a page that uses CSS counters with a decrementing value. Use counter-reset on the body to create a counter called "section", then use counter-increment with a value of -1 on h2::before to decrease the counter. Display "Section X: " before each heading using the content property. Include three h2 elements with paragraph text.
Output: complete HTML page

Incrementing by Custom Values

Any value works as the step. In the example below, the counter goes up by 2.

Example

Prompt
Create a page that uses CSS counters incrementing by 2. Use counter-reset on the body to create a counter called "section", then use counter-increment with a value of 2 on h2::before to increase the counter by 2 each time. Display "Section X: " before each heading using the content property. Include three h2 elements with paragraph text.
Output: complete HTML page