CSS Pseudo-elements
Pseudo-elements create virtual elements that don't exist in HTML — ::before, ::after, ::first-line, ::first-letter, ::placeholder. They're powerful for decorative elements, icons, and tooltips without extra HTML markup.
Pseudo-elements
- ::before — Inserts content BEFORE element's content. Requires content: '' property
- ::after — Inserts content AFTER element's content. Commonly used for decorative elements
- ::first-line — Styles only the first line of text. Changes with element width
- ::first-letter — Styles the first letter. Great for drop-cap effects in articles
- ::placeholder — Styles form input placeholder text
- ::selection — Styles user-selected (highlighted) text. Only color and background-color work
- ::marker — Styles list bullets/numbers directly. Change color, size, content
Pseudo-elements Code
/* Decorative underline */
.heading::after {
content: '';
display: block;
width: 60px;
height: 3px;
background: #E44D26;
margin-top: 8px;
}
/* Required field asterisk */
.required::after {
content: ' *';
color: #e74c3c;
}
/* Drop cap */
.article p::first-letter {
font-size: 3em;
font-weight: bold;
float: left;
line-height: 1;
margin-right: 8px;
color: #E44D26;
}
/* Custom selection color */
::selection {
background: #667eea;
color: white;
}
/* Placeholder styling */
input::placeholder {
color: #aaa;
font-style: italic;
}Tip
The ::before/::after + content: '' + position: absolute pattern is the foundation of most decorative CSS. Underlines, badges, overlays, tooltips, shapes — all built this way. Master this combo to avoid extra HTML.
Selectors target HTML elements for styling
Common Mistake
Forgetting content: '' on decorative ::before/::after elements. Without the content property, the pseudo-element doesn't render — no error, just nothing appears. Even for visual-only elements, content: '' is mandatory.
Practice Task
Add decorative elements using only pseudo-elements: (1) ::after colored underline bar on headings (width: 60px, height: 3px), (2) Required label asterisk via ::after, (3) Custom ::selection colors, (4) Drop-cap with ::first-letter.
Quick Quiz
Key Takeaways
- Pseudo-elements create virtual elements that don't exist in HTML — ::before, ::after, ::first-line, ::first-letter, ::placeholder.
- ::before — Inserts content BEFORE element's content. Requires content: '' property
- ::after — Inserts content AFTER element's content. Commonly used for decorative elements
- ::first-line — Styles only the first line of text. Changes with element width