Pseudo-Elements: ::before and ::after
What you'll learn: How to create decorative content directly with CSS, without adding extra HTML elements.
The Core Idea
Pseudo-elements ::before and ::after let you insert generated content before or after an element's actual content—using only CSS. Think of them as invisible "helper elements" that CSS creates for you. They're perfect for adding decorative touches, icons, or labels without cluttering your HTML with extra <span> or <div> elements.
Analogy: Imagine a picture frame. The actual photo is your HTML content. The ::before pseudo-element is like adding a decorative label at the top of the frame, and ::after is like adding a signature at the bottom—all without touching the photo itself.
How They Work
Both pseudo-elements require a content property to function. Even if you want them empty, you must write content: "";. Once created, they behave like real elements you can style with colors, sizes, positioning, and more.
.quote::before {
content: """;
color: gray;
font-size: 2em;
}
.quote::after {
content: """;
color: gray;
font-size: 2em;
}
This would wrap your quote text with decorative quotation marks—no extra HTML needed!
Common Uses
- Adding icons or symbols (→, ★, •)
- Creating decorative borders or underlines
- Inserting labels like "NEW" or "SALE"
- Adding clearfix solutions for layouts
.new-item::before {
content: "NEW";
background: red;
color: white;
padding: 2px 5px;
margin-right: 5px;
}
Key Takeaway: ::before and ::after let you generate decorative content purely in CSS, keeping your HTML clean and semantic while adding visual enhancements.