iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

PropertyPurpose
counter-resetCreate a counter, start it at a value (default 0).
counter-incrementBump 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 &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Number each question in the FAQ list.

.faq { counter- : q; } .faq .question { counter-increment: q; }

Test yourself

Q1. Which property starts a counter?
Q2. Which property bumps the counter as you traverse the DOM?
Q3. Which function reads the counter inside `content`?

Discussion

Loading…