CSS -counters()
The CSS counters() function allows you to work with nested counters. It provides a combined string that shows the current values of the named counters, if they exist. This function comes in two forms:
counters(name, string)
counters(name, string, style)
A counter's value can be displayed with the content property.
Possible Values
<custom-name> − This is a unique name for the counters that must exactly match the case as used in counter-reset and counter-increment. The name must not begin with two hyphens and cannot be none, unset, initial, or inherit.
<counter-style> − This is optional. The style of the counter (can be a list-style-type value or @counter-style value or symbols() function.). The name of a counting style can be simple, such as numeric, alphabetic, or symbolic etc.
<string> − It gives us the freedom to use as many text characters as needed. When it comes to non-latin characters, they must be represented using their unicode escape sequences.
For example, \000A9 stands for the copyright symbol.
Syntax
counters( <custom-ident>, [, [ <counter-style> | none ] ], <string> )
CSS counters() - Basic Example
This program demonstrates the usage of the counters() function.
<html>
<style>
ul {
list-style: none;
counter-reset: demo-counter;
}
ul li {
counter-increment: demo-counter;
background-color: lightgray;
}
ul li:before {
content: counters(demo-counter, ".") " - ";
color: red;
}
</style>
<ul>
<li>Chapter A
<ul>
<li>Unit- a
<ul>
<li>Sub-unit</li>
<li>Sub-unit</li>
</ul>
</li>
<li>Unit- b
<ul>
<li>Sub-unit</li>
<li>Sub-unit</li>
</ul>
</li>
</ul>
</li>
<li>Chapter B
<ul>
<li>Unit- a
<ul>
<li>Sub-unit</li>
<li>Sub-unit</li>
</ul>
</li>
<li>Unit- b
<ul>
<li>Sub-unit</li>
<li>Sub-unit</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</html>
CSS counters() - Nested Ordered Lists
In the following example, the counters() function is used to dynamically generate content based on a counter named custom-counter.
The counters() function increments and retrieves the value of the specified counter, allowing for the customized formatting of list markers and content in the ordered list elements.
<html>
<head>
<style>
ol {
counter-reset: custom-counter;
}
li {
counter-increment: custom-counter;
}
li::marker {
content:
counters(custom-counter, ".", lower-alpha) ") ";
}
li::before {
content:
counters(custom-counter, ". ") " -- "
counters(custom-counter, "]. ", upper-roman);
}
</style>
</head>
<body>
<ol>
<li>
<ol>
<li></li>
<li></li>
<li></li>
</ol>
</li>
<li>
<ol>
<li></li>
<li></li>
<li></li>
</ol>
</li>
<li></li>
<li>
<ol>
<li></li>
<li>
<ol>
<li></li>
<li></li>
<li></li>
</ol>
</li>
</ol>
</li>
</ol>
</body>
</html>