counter()
The counter()
CSS function returns a string representing the current value of the named counter, if there is one.
It is generally used in the content
property of pseudo-elements, but can theoretically be used anywhere a <string>
value is supported.
/* Simple usage */
counter(countername);
/* changing the counter display */
counter(countername, upper-roman)
A counter has no visible effect by itself.
The counter()
function (and counters()
function) is what makes it useful by returning developer defined strings (or images).
Syntax
Values
<custom-ident>
-
A name identifying the counter, which is the same case-sensitive name used for the
counter-reset
andcounter-increment
. The name cannot start with two dashes and can't benone
,unset
,initial
, orinherit
. <counter-style>
-
A
<list-style-type>
name,<@counter-style>
name orsymbols()
function, where a counter style name is anumeric
,alphabetic
, orsymbolic
simple predefined counter style, a complex longhand east Asian or Ethiopic predefined counter style, or other predefined counter style. If omitted, the counter-style defaults todecimal
.
Formal syntax
counter( <counter-name>, <counter-style>? )where
<counter-name> = <custom-ident>
<counter-style> = <counter-style-name> | symbols()where
<counter-style-name> = <custom-ident>
Examples
default value compared to upper Roman
HTML
<ol>
<li></li>
<li></li>
<li></li>
</ol>
CSS
ol {
counter-reset: listCounter;
}
li {
counter-increment: listCounter;
}
li::after {
content: "[" counter(listCounter) "] == ["
counter(listCounter, upper-roman) "]";
}
Result
decimal-leading-zero compared to lower-alpha
HTML
<ol>
<li></li>
<li></li>
<li></li>
</ol>
CSS
ol {
counter-reset: count;
}
li {
counter-increment: count;
}
li::after {
content: "[" counter(count, decimal-leading-zero) "] == ["
counter(count, lower-alpha) "]";
}
Result
Specifications
Specification |
---|
CSS Lists and Counters Module Level 3 # counter-functions |
Browser compatibility
BCD tables only load in the browser