Using before and after Pseudo-elements
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
What a Pseudo-element Is
Unlike a pseudo-class (which targets an existing element in a certain state), a pseudo-element lets CSS create and style a piece of content that is not a real element in the HTML at all. ::before and ::after insert generated content just inside an element, at its start or end.
The Required content Property
.required::after {
content: " *";
color: red;
}Without a content property, ::before and ::after do not render at all - even an empty string, content: "";, is required to make them appear.
Adding Decorative Shapes Without Extra Markup
.quote::before {
content: "\201C"; /* an opening curly quote character */
font-size: 2rem;
color: #cccccc;
}This is a common technique for adding decorative quotation marks, icons, or small shapes without cluttering the HTML with extra empty <span> elements purely for styling purposes.
A Classic Use: The Clearfix Hack
.clearfix::after {
content: "";
display: table;
clear: both;
}Before Flexbox and Grid existed, this was the standard way to fix a container collapsing to zero height when it only contained floated children.
Things to Remember
- Generated content is not part of the accessible DOM by default and is generally ignored by screen readers - never put essential information only inside
content. ::beforeand::afterare inline by default; settingdisplay: blockorinline-blockis often needed to size or position them.- They cannot be added to certain elements, such as
<img>, which have no way to render child content.