CSS Counter

The CSS counter is set by a variable, and the variable is incremented according to the rule.

Automatic numbering using counter

The CSS counter increments the variable according to the rules.

The following properties are used in CSS counters:

  • counter-reset -Create or reset counter
  • counter-increment -Increment variable
  • content -Insert generated content
  • counter()Or counters()function – to add the value of the counter element

To use a CSS counter, you must first create it with counter-reset:

The following example creates a counter on the page (in the body selector), the count value of each <h2> element will be incremented, and add “Section < count value >:” before each <h2> element

Example

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

Nested counter

The following example creates a counter on the page, and adds the counter value “Section < main title counter value >.” before each <h1> element , and the nested counter value is placed in front of the <h2> element with the content “< main Title count value >.< Subtitle count value >”:

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, and the child elements of the list are automatically created. Here we use the counters()function inserts a string in different nested hierarchy:

Example

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

CSS counter properties

Attributes description
content Use ::before and ::after pseudo-elements to insert automatically generated content
counter-increment Increment one or more values
counter-reset Create or reset one or more counters