counter() CSS Function

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

Description

The CSS counter() function returns the current value of a named counter. Counters are variables maintained by CSS whose values can be incremented or decremented by CSS rules that track how many times they're used. You can define your own named counters, and you can also manipulate the list-item counter that is created by default for all ordered lists.

The counter() function takes two arguments:

  1. The name of the counter.
  2. A string that will be displayed before or after the counter value.

The counter() function can be used anywhere a string value is supported, but it is most commonly used in the content property of pseudo-elements. For example, you can use the following CSS to automatically number the headings in a webpage:

h1:before {
  content: counter(h1, ". ");
}

This will insert the value of the h1 counter, followed by a period and a space, before each h1 element.

The counter() function can also be used to create nested counters. For example, you can use the following CSS to create a table of contents with nested headings:

h2:before {
  content: counter(h2, ". ") counter(h3, ". ");
}

h3:before {
  content: counter(h3, ". ");
}

This will insert the value of the h2 counter, followed by a period and a space, followed by the value of the h3 counter, followed by a period and a space, before each h2 element. The value of the h3 counter will be reset for each h2 element.

Syntax

<counter()> = counter( <counter-name> , <counter-style>? )

Values

  • <counter-name>
  • <counter-style>

Example

<h1>Using CSS Counters:</h1>
<h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h2>JavaScript Tutorial</h2>
body {
counter-reset: section;
}

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

Browser Support

The following table will show you the current browser support for the CSS counter() function.

Desktop
Edge Chrome Firefox Opera Safari
12119.23
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
18410.1114.4

Last updated by CSSPortal on: 7th October 2023