CSS Counters

Using CSS Counters

The CSS counter is set by a variable, which is incremented according to the rules.

CSS counters increment variables based on rules.

CSS counters use the following attributes:

  • counter-reset -create or reset a counter
  • counter-increment -increment variable
  • content -Insert the generated content
  • counter () or counters () function-add the value of a counter to an element

To use CSS counters, you must first create them with counter-reset:


body {
    counter-reset: section;

h2::before {
    counter-increase: section;
    content: "Section " counter(section) ": ";
Try it yourself »

Nesting Counters

The following example creates a counter on the page (in the body selector), the count value of each <h2> element is incremented, and "Section "count value<:" is added before each



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 can also be used in lists, and child elements of the list are automatically created. Here we use the counters () function to insert strings in different levels of nesting:


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