CHAPTER 38

CSS Counters

Learn how CSS counters can automatically number elements without manually writing numbers in HTML.

01. What is CSS Counters?

CSS counters automatically track numerical values.
The counter-reset property creates or resets a counter.
The counter-increment property increases the counter.
The counter() function displays the current counter value.

02. Syntax

container { counter-reset: section; } item { counter-increment: section; } item::before { content: counter(section); }

03. Example

CSS / HTML Example AIFA Coding Lab
<!DOCTYPE html>
<html>
<head>

<style>

body {

    counter-reset: lesson;

}

h2 {

    counter-increment: lesson;

}

h2::before {

    content:
        "Lesson "
        counter(lesson)
        ": ";

    color: #2563eb;

}

</style>

</head>

<body>

<h2>HTML</h2>

<h2>CSS</h2>

<h2>JavaScript</h2>

</body>
</html>

04. Important Points

✓ counter-reset initializes a counter.
✓ counter-increment increases the counter.
✓ counter() displays the counter value.
✓ Counters are useful for automatically numbered content.

05. Common Mistakes

⚠ Forgetting counter-reset.
⚠ Incrementing the wrong element.
⚠ Using counters when normal HTML numbering would be clearer.

06. Real World Use

CSS counters can be useful for chapters, documentation, numbered sections and automatically numbered lists.

Ready to Practice? 🚀

Open the AIFA CSS Editor and practice this chapter live.

Try It Yourself →
Practice Exercise

Create Numbered Sections

Create five headings and use CSS counters to automatically number them.