CSS Counters & Generated Content
CSS counters automatically number elements — sections, headings, steps, figures. Combined with generated content (::before/::after), they create automatic numbering without any JavaScript or manual HTML numbering.
Counter Properties
- counter-reset: name — Initialize a counter (usually on parent): counter-reset: section
- counter-increment: name — Increment the counter (on each item): counter-increment: section
- counter(name) — Display the counter value in content property: content: counter(section)
- counters(name, '.') — Nested counters with separator: 1.1, 1.2, 2.1, etc.
- Custom formatting — counter(name, decimal-leading-zero) = 01, 02, 03...
- content property — Can combine text and counters: content: 'Step ' counter(step) ': '
- counters + ::before — The standard pattern for automatic numbering in CSS
CSS Counters Code
/* Automatic section numbering */
.article { counter-reset: section; }
.article h2 { counter-increment: section; }
.article h2::before {
content: counter(section) '. ';
color: #E44D26;
font-weight: 800;
}
/* Step numbering with circles */
.steps { counter-reset: step; list-style: none; padding: 0; }
.steps li { counter-increment: step; padding-left: 40px; position: relative; margin-bottom: 16px; }
.steps li::before {
content: counter(step);
position: absolute;
left: 0;
width: 28px; height: 28px;
background: #667eea;
color: white;
border-radius: 50%;
display: flex; align-items: center; justify-content: center;
font-weight: bold; font-size: 0.85em;
}
/* Figure numbering */
.content { counter-reset: fig; }
figure { counter-increment: fig; }
figcaption::before { content: 'Figure ' counter(fig) ': '; font-weight: 600; }Tip
CSS counters are perfect for numbered step guides and figure captions. They update automatically when you add/remove elements — no manual renumbering. Use counters(name, '.') for hierarchical numbering like 1.1, 1.2.
Selectors target HTML elements for styling
Common Mistake
Putting counter-reset on each item instead of the parent. counter-reset initializes the counter to 0 — if placed on each li, every item shows '1'. Always put counter-reset on the PARENT and counter-increment on each CHILD.
Practice Task
Build auto-numbered content: (1) Steps list with circular numbered badges via ::before, (2) Article h2 headings auto-numbered as '1. Introduction', '2. Setup', (3) Figures with auto-numbered captions: 'Figure 1:', 'Figure 2:'.
Quick Quiz
Key Takeaways
- CSS counters automatically number elements — sections, headings, steps, figures.
- counter-reset: name — Initialize a counter (usually on parent): counter-reset: section
- counter-increment: name — Increment the counter (on each item): counter-increment: section
- counter(name) — Display the counter value in content property: content: counter(section)