CSS Pseudo-element Selectors (::before, ::after) — Generated Content
Learn CSS pseudo-element selectors ::before, ::after, ::first-line, and ::first-letter. Create decorative content, icons, and visual effects without extra HTML markup.
Detailed Explanation
CSS Pseudo-element Selectors
Pseudo-elements create virtual elements that don’t exist in the DOM, allowing you to style specific parts of an element or insert generated content without additional HTML.
Double Colon Syntax
Modern CSS uses :: for pseudo-elements to distinguish them from pseudo-classes (:):
p::before { } /* correct */
p::after { } /* correct */
p:before { } /* legacy, still supported */
::before and ::after
The most commonly used pseudo-elements. They require the content property:
.required-field::after {
content: " *";
color: red;
}
.external-link::after {
content: " ↗";
font-size: 0.8em;
}
blockquote::before {
content: "\201C"; /* opening quote */
font-size: 3rem;
color: #ccc;
}
Decorative Patterns
/* Underline effect */
.fancy-link::after {
content: "";
display: block;
width: 0;
height: 2px;
background: currentColor;
transition: width 0.3s;
}
.fancy-link:hover::after {
width: 100%;
}
/* Clearfix */
.clearfix::after {
content: "";
display: table;
clear: both;
}
::first-line and ::first-letter
article p::first-letter {
font-size: 3em;
float: left;
line-height: 1;
margin-right: 0.1em;
}
article p::first-line {
font-variant: small-caps;
}
Specificity
Pseudo-elements add (0, 0, 1) to specificity — the same as a type selector.
Important Notes
::beforeand::afterdon’t work on replaced elements (<img>,<input>,<br>)- Content added via pseudo-elements is not accessible to screen readers by default
- You cannot select pseudo-element text with the mouse
Use Case
Pseudo-elements are essential for decorative CSS without polluting HTML structure. They power CSS-only icons, custom list markers, tooltip arrows, animated underlines, quotation marks, badge indicators, clearfix hacks, and ornamental borders. Front-end developers use them extensively to keep HTML semantic while adding visual embellishments through CSS.