::before, ::after & counters
Content from CSS
Lesson 7 of 20 · 10 min · Module 2: Selectors and the cascade
Some visual details are decoration rather than content: the number in a step badge, or the asterisk after a required label. Pseudo-elements add them from CSS, so the HTML stays clean.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Add decorative content with ::before and ::after
- Number elements automatically with counters
- Know when content belongs in the HTML instead
The idea
::before and ::after create an extra box at the start or end of an element, and only appear when they have a content value. CSS counters number things for you: counter-reset starts a counter, counter-increment adds one, and content: counter(step) prints it.
blockquote::before {
content: "“";
font-size: 48px;
color: #2f6f4e;
}
01No content, no box
A pseudo-element only exists when content is set, even to an empty string. content: "" is common for purely decorative shapes such as dots and lines.
02Counters count for you
counter-reset: step starts the count on the list. Each li::before adds one with counter-increment and prints the value. Insert a new step and every number updates by itself.
.steps { counter-reset: step; }
.steps li::before {
counter-increment: step;
content: counter(step);
}
03Decoration, not information
Screen readers may or may not announce generated content, and it cannot be selected or translated reliably. The asterisk is a visual hint; the required attribute on the input is what tells everyone that the field is required.
Your turn
.steps set counter-reset: step. On .steps li::before set counter-increment: step and content: counter(step), and turn it into a round badge with width: 28px; height: 28px; border-radius: 50%; background: #2f6f4e; color: #ffffff; display: grid; place-items: center;. 2) Add a red marker after required labels: label.required::after { content: " *"; color: #b42318; }.What the checks look for
- The steps list starts a counter
- Every step shows its number
- Numbers sit in green badges
- The badges are round
- Required labels end with " *"
- The marker is red
- Optional labels have no marker
Take this with you
Pseudo-elements and counters add decoration while the HTML stays meaningful.
Go a little further
Show letters instead of numbers with counter(step, upper-alpha), or nest a second counter for sub-steps.