CSS Counters
CSS counters are like variables you can increment in the stylesheet. They're how you build custom numbering — chapters, footnotes, ordered FAQs — without touching the HTML.
The three properties
| Property | Purpose |
|---|---|
counter-reset | Create a counter, start it at a value (default 0). |
counter-increment | Bump the counter when this element is reached. |
counter() / counters() | Read it back inside a content value. |
Numbered FAQ
CSS
.faq { counter-reset: q; }
.faq .question {
counter-increment: q;
}
.faq .question::before {
content: "Q" counter(q) ". ";
color: #04AA6D;
font-weight: bold;
}
Nested numbering with counters()
CSS
ol.outline { counter-reset: section; list-style: none; padding-left: 1em; }
ol.outline li { counter-increment: section; }
ol.outline li::before {
content: counters(section, ".") " "; /* renders 1, 1.1, 1.1.1 */
font-weight: bold;
}
Tip: Counters live in the cascade — they're scoped to the element that declared them and reset whenever you re-declare them. Pair with
::before + content for almost any numbering scheme you can dream up.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Counters</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Number each question in the FAQ list.
.faq { counter-
: q; } .faq .question { counter-increment: q; }
You declare the counter with counter-?
Discussion
Loading…