CSS Counter


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


Automatic Numbering Using CSS 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() ocounters() 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) ": ";
}

 Try It! 


Nested CSS 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 counter value>.<subtitle counter 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) "";
}

 Try It! 

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

 Try It! 


CSS Counter Properties

PropertyDescription
contentUse ::before and ::after pseudo-elements to insert automatically generated content
counter-incrementIncrement one or more values
counter-resetCreate or reset one or more counters