counter-set: [ <counter-name> <integer>? ]+ | none
counter-reset: [ <counter-name> <integer>? ]+ | none
counter-increment: [ <counter-name> <integer>? ]+ | none
counter(<counter-name> [, <counter-style> ]?)
counters(<counter-name>, <connector-string> [, <counter-style> ]?)
|counter-name||This is the name of the counter that needs to be created or incremented or printed. It can be any custom name as the developer wishes.|
|integer||This integer is an optional value that when provided next to the counter name will represent the initial value of the counter (in |
|none||This is the initial value for all 3 |
|counter-style||This specifies the style in which the counter value needs to be displayed. It supports all values supported by the |
|connector-string||This represents the string that must be placed between the values of two different counter levels (like the "." in "2.1.1").|
Counters are not a new topic in CSS. It was a part of the CSS Level 2 Specifications (Revision 1 to be precise) itself and hence has very high browser support.
All browsers except IE6 and IE7 have support for CSS Counters.
Applying roman numerals styling to the counter output
In the above example, the counter's output would be displayed as I, II, III (roman numbers) instead of the usual 1, 2, 3 as the developer has explicitly specified the counter's style.
Implementing multi-level numbering using CSS counters
The above is an example of multi-level numbering using CSS counters. It makes use of the self-nesting concept of counters. Self nesting is a concept where if an element already has a counter with the given name but is having to create another then it creates it as a child of the existing counter. Here, the second level
ul already inherits the
list-item-number counter from its parent but then has to create its own
list-item-number (for its children
li) and so creates
list-item-number (counter for second level) and nests it under
list-item-number (counter for first level). Thus it achieves the multi-level numbering.
The output is printed using the
counters() function instead of the
counter() function because the
counters() function is designed to prefix the value of all higher level counters (parent) when printing the output.
Number each item using CSS Counter
The above example numbers every "item" in the page and adds the item's number before its header (using
content property of
:before pseudo). A live demo of this code is available here.