What are CSS pseudo-elements and how do you use ::before and ::after?
· Category: HTML & CSS
Short answer
Pseudo-elements create virtual elements that are not in the DOM. ::before inserts content before an element's actual content; ::after inserts content after it.
How it works
Pseudo-elements require a content property, even if it is an empty string. They inherit styles from their parent element and can be styled like any real element. Common use cases include decorative icons, quotes, custom underlines, and clearfixes.
Example
.quote::before {
content: open-quote;
font-size: 2rem;
color: gray;
}
.quote::after {
content: close-quote;
font-size: 2rem;
color: gray;
}
.link::after {
content: ' →';
}
Tips
- Use
content: ""when you only need a styled shape or overlay. - Pseudo-elements cannot be targeted by JavaScript directly, but they react to parent events.
- Remember the double-colon syntax (
::before) for CSS3, though single-colon works for backward compatibility.