CSS ::before and ::after - Generated Content Guide
Master CSS ::before and ::after pseudo-elements for generated content, decorative elements, tooltips, and clearfixes. Learn content property, positioning, and accessibility.
Detailed Explanation
::before and ::after Pseudo-elements
The ::before and ::after pseudo-elements create virtual child elements at the start and end of the selected element. They require the content property and are extremely versatile for decorative and functional purposes.
Syntax
.element::before {
content: "prefix";
/* additional styles */
}
.element::after {
content: "suffix";
/* additional styles */
}
The content Property
The content property is required — without it, the pseudo-element does not render:
content: "text"; /* String */
content: ""; /* Empty (for decorative use) */
content: attr(data-label); /* From an attribute */
content: url(icon.svg); /* Image */
content: counter(item); /* CSS counter */
content: "(" attr(href) ")"; /* Combined */
Decorative Elements
/* Decorative line under headings */
h2::after {
content: "";
display: block;
width: 60px;
height: 3px;
background: #3b82f6;
margin-top: 8px;
}
Icon Indicators
/* External link indicator */
a[href^="https://"]::after {
content: " \2197"; /* ↗ arrow */
font-size: 0.8em;
}
/* Required field indicator */
label.required::after {
content: " *";
color: red;
}
Clearfix (Legacy)
.clearfix::after {
content: "";
display: table;
clear: both;
}
Specificity
Both ::before and ::after contribute specificity equivalent to one element selector: (0, 0, 1).
Accessibility Warning
Content added via ::before and ::after is generally not accessible to screen readers in a reliable way. Never use pseudo-elements for critical content — use them only for decorative or supplementary visuals. Use aria-hidden="true" when pseudo-element content could confuse assistive technology.
Use Case
The ::before and ::after pseudo-elements are used extensively for decorative elements (underlines, badges, icons), form field indicators (required asterisks), clearfixes (legacy float layouts), custom list markers, tooltips, and CSS-only shapes. They allow adding visual content without cluttering HTML, keeping markup semantic and clean.