CSS Counters


🔹 What are CSS Counters?

CSS Counters are variables maintained by CSS to keep track of how many times something appears. They are commonly used to create automatic numbering for elements like headings, sections, figures, or list items — without adding extra HTML or JavaScript.

You define, increment, and display counters using special CSS properties.


🔸 Key Properties

Property Purpose
counter-reset Initializes or resets the counter
counter-increment Increases the counter’s value
content: counter() Displays the counter's current value

🔸 Basic Example: Numbering Headings

<h2>Introduction</h2>
<h2>Getting Started</h2>
<h2>Conclusion</h2>
body {
  counter-reset: section; /* initialize */
}

h2::before {
  counter-increment: section; /* increase */
  content: "Section " counter(section) ": ";
}

Output:

Section 1: Introduction
Section 2: Getting Started
Section 3: Conclusion

🔸 Nested Counters (Multi-level)

body {
  counter-reset: chapter;
}

h1 {
  counter-reset: section;
}

h1::before {
  counter-increment: chapter;
  content: "Chapter " counter(chapter) " - ";
}

h2::before {
  counter-increment: section;
  content: counter(chapter) "." counter(section) " ";
}

🔸 Changing Counter Style

CSS supports numeric, Roman, and alphabetic styles:

content: counter(chapter, upper-roman);
  • decimal (default)

  • upper-roman (I, II, III...)

  • lower-alpha (a, b, c...)


Practice Questions

✅ Write CSS for the following:

Q1. Automatically number all <h2> elements.

Q2. Create a counter that numbers list items without using <ol>.

Q3. Use Roman numerals to number sections.

Q4. Implement nested counters for chapters and sections.

Q5. Reset a counter inside each new <h1>.

Q6. Add leading zero (e.g., 01, 02) in the numbering.

Q7. Display section numbers using uppercase letters.

Q8. Customize counter style using ::before.

Q9. Apply counters to figure captions automatically.

Q10. Use multiple independent counters on the same page.


Go Back Top