-
Hajipur, Bihar, 844101
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.
Property | Purpose |
---|---|
counter-reset |
Initializes or resets the counter |
counter-increment |
Increases the counter’s value |
content: counter() |
Displays the counter's current value |
<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
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) " ";
}
CSS supports numeric, Roman, and alphabetic styles:
content: counter(chapter, upper-roman);
decimal
(default)
upper-roman
(I, II, III...)
lower-alpha
(a, b, c...)
✅ 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.
Q1: Which property initializes a CSS counter?
Q2: Which property displays a counter value?
Q3: What does counter-increment do?
Q4: Which pseudo-element is commonly used with counters?
Q5: How to use uppercase Roman numerals in counters?
Q6: Can counters be nested?
Q7: Which CSS property is used to reset a nested counter?
Q8: Where can you use CSS counters?
Q9: What is the default style of counters?
Q10: Which of the following is valid syntax for displaying a counter?