Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

CSS Counters

CSS Counters

CSS counters are set up through a variable that is incremented according to rules.


Automatic Numbering with Counters

CSS counters increment a variable according to rules.

CSS counters use the following properties:

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

The following example creates a counter on the page (in the body selector). Each

element's counter value is incremented, and before each

element, "Section" <counter value>:"

CSS example

body

{

counter-reset:

section

;

}

h2

:

:before

{

counter-increment:

section

;

content:

"

Section

"

counter

(

section

) ": "

;

}

Try it »


Nested Counters

The following example creates a counter on the page. Before each

element, it adds the counter value "Section" <main heading counter value>", and the nested counter value is placed

before the element, with the content "<main heading counter value>.<subheading 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

) " "

;

}

Try it »

Counters can also be used in lists, where the list items are created automatically. Here we use the counters() function to insert strings at different nesting levels:

CSS example

ol

{

counter-reset:

section

;

list-style-type:

none

;

}

li

:

:before

{

counter-increment:

section

;

content:

counters

(

section

,".") " "

;

}

Try it »


CSS Counter Properties

property Description
content Used to insert auto-generated content with the ::before and ::after pseudo-elements
counter-increment Increments one or more values
counter-reset Creates or resets one or more counters.