3.0 KiB
Counter
Counters are, in essence, variables maintained by CSS whose values may be incremented by CSS rules to track how many times they're used.
HTML
<section class="countable-section">
<div class="countable-item">
<p>Some item</p>
<div class="countable-section">
<p>First sub item</p>
<p>Second sub item</p>
<p>Third sub item</p>
</div>
</div>
<div class="countable-item">
<p>Second other item</p>
</div>
<div class="countable-item">
<p>Third item</p>
</div>
<div class="countable-item">
<p>Fourth item</p>
</div>
</section>
CSS
.countable-section {
counter-reset: counter1;
}
.countable-item p {
counter-increment: counter1;
}
.countable-item p:before {
content: counters(counter1, '-') ' ';
font-weight: bold; /* for better visualization on demo */
}
Demo
Some item
First sub item
Second sub item
Third sub item
Second other item
Third item
Fourth item
Explanation
You can create a ordered list using any type of HTML.
-
counter-resetInitializes a counter, the value is the name of the counter. By default, the counter starts in 0. This property can also be used to change its value to any specific number. -
counter-incrementUsed in element that will be countable. Oncecounter-resetinitialized, a counter's value can be increased or decreased. -
counter(variable_name, style)Displays the value of a section counter. Generally used in acontentproperty. This function can recieve two parameters, the first as the name of the counter and the second one can bedecimalorupper-roman(decimalby default). -
counters(variable_name, separator, style)Displays the value of a section counter. Generally used in acontentproperty. This function can recieve three parameters, the first as the name of the counter, the second one you can include a string which comes after the counter and the third one can bedecimalorupper-roman(decimalby default). -
A CSS counter can be especially useful for making outlined lists, because a new instance of the counter is automatically created in child elements. Using the
counters()function, separating text can be inserted between different levels of nested counters.
Browser support
✅ No caveats.