Topic 20 of 30
Pseudo-Elements
Overview
Pseudo-elements create virtual sub-elements that can be styled without adding HTML. ::before and ::after are used for decorative effects, icons, and overlays. ::first-line and ::placeholder improve typography and forms.
Syntax
css
/* ::before and ::after — require content property */
.card::before {
content: "";
position: absolute;
inset: 0;
background: linear-gradient(135deg, gold 0%, transparent 100%);
opacity: 0.05;
}
/* Counter badge */
.nav-item::after {
content: attr(data-count); /* from HTML attribute */
background: gold;
color: #000;
border-radius: 50%;
padding: 2px 6px;
font-size: 12px;
}
/* ::placeholder */
input::placeholder { color: #666; font-style: italic; }
/* ::selection */
::selection { background: gold; color: #000; }
/* ::first-line, ::first-letter */
p::first-letter { font-size: 2em; font-weight: bold; color: gold; }Common Pitfalls
- ::before and ::after are inline by default — add display:block or position:absolute for layout control.
- content: '' (empty string) is required for decorative pseudo-elements — omitting content makes them invisible.
- Interview tip: Pseudo-elements use double colons (::) in CSS3 — single colon (:) is the old CSS2 syntax. Both work but :: is standard.
Real-World Example
Decorative quote card and tooltip using pseudo-elements:
example
css
/* Blockquote with decorative quotes */
blockquote {
position: relative;
padding: 24px 24px 24px 56px;
}
blockquote::before {
content: '"';
position: absolute;
left: 12px;
top: 0;
font-size: 5rem;
color: #FFD700;
line-height: 1;
font-family: Georgia, serif;
}
/* Tooltip using ::after */
[data-tooltip]::after {
content: attr(data-tooltip);
position: absolute;
bottom: calc(100% + 8px);
left: 50%;
transform: translateX(-50%);
background: #1a1a1a;
color: #fff;
padding: 6px 12px;
border-radius: 6px;
font-size: 13px;
white-space: nowrap;
pointer-events: none;
opacity: 0;
transition: opacity 0.2s;
}
[data-tooltip]:hover::after { opacity: 1; }