Counter

This page lists the CSS properties related to counters.

Counters are "variables" maintained by CSS whose values can be incremented by CSS rules (MDN). You can use counters, for example, to automatically number the headings in the document.

| LIVE PREVIEW

Nama Mugi

Nama Gome

Nama Tamago

Basic Concepts

Using Counters

To use CSS counter, it must first be initialized to a value using counter-reset. Once initialized, a counter's value can be increased or decreased with counter-increment.

Displaying Counter's Value

The value of a counter can be displayed using the counter(...) or counters(...) function in a content property.

For example,

h2::before {
  /* Will prepend "Chapter <number>: " */
  content: 'Chapter ' counter(chapter) ': ';
  counter-increment: chapter;
}

CSS Properties

counter-reset

Instantiates the specified counter name and sets its value to the specified number (defaults to 0).

h2 {
  /* instantiate and set the value to 0 */
  counter-reset: my-counter;
  counter-reset: my-counter 0;
  /* instantiate and set the value to 1 and 4 respectively */
  counter-reset: counter-a 1 counter-b 2;
}

counter-increment

Increments the specified counter name with the specified number (defaults to 1).

h2 {
  /* increment by 1 */
  counter-reset: my-counter;
  counter-reset: my-counter 1;
  /* increment by 2 and -3 respectively */
  counter-reset: counter-a 2 counter-b -3;
}

counter-set

Manipulates the value of existing counters. (Only instantiates a new counter if there is no counter of the given name on the element yet.)

h2 {
  /* set the value to 0 */
  counter-set: my-counter;
  counter-set: my-counter 0;
  /* set the value to 1 and 4 respectively */
  counter-set: counter-a 1 counter-b 2;
}

CSS Functions

The style argument for these functions are optional. If you want to supply the value, you can use any value from list-style-type.

counter(counterName, style)

Returns the current value of counterName, and optionally format it using list-style-type of style.

For example, counter(my-counter, lower-roman) will return i, ii, iii, etc.

h3::before {
  counter-increment: section;
  content: 'Section ' counter(section) ': ';
}

counters(counterName, separator, style)

Enables nested counters: returns the current value of counterName (taking account of nesting), separated using separator, and optionally format it using list-style-type of style.

For example, counters(my-counter, '.', decimal) can return something like 1, 1.1, 1.2.3, 2. etc.

| LIVE PREVIEW

References