CSS counters are variables that are maintained and manipulated by CSS rules to count the number of times they have been used within the document using the counter-increment, counter-set, counter-reset properties, and read with counter() and counters(). Their value is inaccessible outside of CSS and are generally used as pseudo-element content. Add this tag for questions relating to the usage of CSS counters. For other types of counters, use the [css] tag.
Description
CSS counters are variables that are maintained and manipulated by CSS rules to count the number of times they have been used within the document.
Counter Manipulation
The value of the counter variable can be modified by using either of the following properties:
Counter Reset - This sets the value of the counter to either 0 (default) or a specified value. This is the first step in the usage of counters as it initializes the counter variable.
Syntax is counter-reset: [counter-name] [value]
.
Multiple counters can also be reset at the same time by providing the counter names and its values in a space separated manner (like counter-reset: counter1 3 counter2 5;
).
Counter Increment - This increments the value of counter every-time the CSS selector rule is matched. The default incrementation is by 1 but similar to the counter reset property, here also the incrementation factor can be specified.
Syntax is counter-increment: [counter-name] [incrementation-factor]
.
Again similar to the counter reset property, here also multiple counters can be incremented at the same time by using a space separated list.
Counter Value Display
All counter values can currently be displayed only by using the content
property of a pseudo-element. It is also possible to style the counter by specifying the style as the second argument. The list of supported values are the same as for the list-style-type property.
Syntax is content: counter([counter-name], [counter-style])
.
The counter values are not accessible outside of CSS (that is, their value currently cannot be read using JavaScript or the likes).
Example: Below is a sample snippet which counts the no. of rows in a table and dynamically adds the row number to every row. Here is a sample fiddle which shows the below code in action.
table {
counter-reset: rows; /* initialize the counter */
}
tr {
counter-increment: rows; /* increment the counter for every tr encountered */
}
td:first-child:before {
content: counter(rows)". "; /* display the value of the counter */
}