Easy Tutorial
❮ Css Combinators Pr List Style Image ❯

CSS Counters

CSS counters are set using a variable that increments according to specified rules.


Automatic Numbering with Counters

CSS counters increment variables based on rules.

CSS counters involve the following properties:

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

The following example creates a counter on the page (in the body selector), increments the counter value for each <h2> element, and adds "Section <counter value>:" before each <h2> element.

CSS Example

body {
  counter-reset: section;
}

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

Nested Counters

The following example creates a counter on the page, adds the counter value "Section <main counter value>." before each <h1> element, and nested counter values before each <h2> element with the content "<main counter value>.<sub counter value>":

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

Counters can also be used in lists, where child elements automatically create nested counters. Here, we use the counters() function to insert strings at different nested levels:

CSS Example

ol {
  counter-reset: section;
  list-style-type: none;
}

li::before {
  counter-increment: section;
  content: counters(section,".") " ";
}

CSS Counter Properties

Property Description
content Uses ::before and ::after pseudo-elements to insert automatically generated content
counter-increment Increments one or more values
counter-reset Creates or resets one or more counters
❮ Css Combinators Pr List Style Image ❯