Topic 17 of 30
Pseudo-elements
Overview
Pseudo-elements (::before, ::after, ::first-line, etc.) create virtual elements that don't exist in HTML, allowing decorative content and effects without cluttering markup.
Syntax
css
/* ::before and ::after */
.badge::before {
content: '🔥';
margin-right: 4px;
}
.divider::after {
content: '';
display: block;
height: 2px;
background: linear-gradient(90deg, gold, transparent);
}
/* Text pseudo-elements */
p::first-line { font-weight: bold; }
p::first-letter { font-size: 2em; float: left; }
/* Selection styling */
::selection {
background: rgba(255, 215, 0, 0.3);
color: #fff;
}Common Pitfalls
- ::before and ::after require content: '' property to display — even for empty decorative elements.
- Pseudo-elements are inline by default — add display:block or position:absolute for layout control.
- Interview tip: :: (double colon) is the modern syntax for pseudo-elements; single colon : worked in older CSS but :: is standard.
Real-World Example
A decorative divider and required field marker using pseudo-elements:
example
css
/* Underline effect on nav links */
.nav-link {
position: relative;
}
.nav-link::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 2px;
background: #FFD700;
transition: width 0.3s ease;
}
.nav-link:hover::after,
.nav-link.active::after {
width: 100%;
}
/* Required field asterisk */
label.required::after {
content: ' *';
color: #ef4444;
}
/* Tooltip using pseudo-element */
[data-tooltip]::after {
content: attr(data-tooltip);
position: absolute;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
background: #1a1a1a;
color: #fff;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
white-space: nowrap;
pointer-events: none;
}