Skip to main content

CSS Counters

By SamK
0
0 recommends
Topic(s)

CSS counters are mostly used to automatically number lists or sections in a webpage.

CSS counters function like variables that can be managed through CSS rules, allowing you to keep track of their usage by incrementing their values.

They allow you to modify the styling of content based on its position within the document.

To use CSS counters, you can use the following properties:

  • counter-reset: Creates or resets a counter.
  • counter-increment: Increments a counter's value.
  • content: Inserts generated content.
  • counter() or counters() function: Adds the counter’s value to an element.

In the following example, a counter is setup using counter-reset on the body element with the name section and then each <h2> element increments this counter. The counter value is used to prepend "Counter:" to each <h2> element.

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

CSS Counter Demo

Nesting Counters

The following example sets up two counters:

  1. One for the page (section)
  2. One for each <h1> element (subsection). 

The section counter is used to number each <h1> element with "Section Counter:", while the subsection counter is used to number each <h2> element with "Counter . Sub-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) " ";
}

Nesting Counters Demo

Outlined Lists and Custom Separators

To use CSS counters for creating outlined lists and include custom separators between different levels, you can use the counters() function along with the content property.

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

Counters Demo

Questions & Answers