Counters in CSS
? Counters in CSS
CSS counters let you create automatic numbering for elements — great for lists, sections, figures, etc. They work like variables that increment as the page is rendered.
How CSS Counters Work
Create a counter with
counter-reset.Increment the counter with
counter-increment.Display the counter value with the
contentproperty andcounter()function.
Basic Example: Numbered Sections
<h2>Chapter 1</h2><h2>Chapter 2</h2><h2>Chapter 3</h2>body { counter-reset: chapter; /* Initialize counter */}h2::before { counter-increment: chapter; /* Increase counter */ content: "Chapter " counter(chapter) ": "; font-weight: bold;}Result:
Chapter 1 Chapter 1
Chapter 2 Chapter 2
Chapter 3 Chapter 3
Multiple Counters & Nesting
For example, numbered lists with sublists:
<ol> <li>First <ol> <li>Sub first</li> <li>Sub second</li> </ol> </li> <li>Second</li></ol>ol { counter-reset: item; list-style: none;}ol > li { counter-increment: item;}ol > li::before { content: counter(item) ". ";}ol > li > ol { counter-reset: subitem;}ol > li > ol > li { counter-increment: subitem;}ol > li > ol > li::before { content: counter(item) "." counter(subitem) " ";}Useful Properties
counter-reset: name [number]— starts or resets a counter.counter-increment: name [number]— increases a counter.content: counter(name)— inserts the current value.You can also use
counters(name, separator)for nested counters.
Summary
| Property | Purpose |
|---|---|
counter-reset | Initialize or reset a counter |
counter-increment | Increase a counter's value |
content: counter() | Display counter value |
Want me to help you build a complex numbered list or a custom counter effect?