CSS Pseudo-elements
Where pseudo-classes target an element's state, pseudo-elements target a
specific part of an element or inject virtual content that has no HTML equivalent. Written with
double colons (::), pseudo-elements let you add decorative shapes,
tooltip arrows, custom list markers, drop caps, custom text selection colours, and styled placeholders — all
in CSS alone.
:: vs
:)
::before and ::after — content injectioncontent property — all
values::first-line and ::first-letter::selection, ::placeholder, ::marker::backdrop, ::spelling-error, modern pseudo-elementsPseudo-elements vs Pseudo-classes
The double colon (::) distinguishes
pseudo-elements from pseudo-classes (:). Both notations work for old
pseudo-elements like :before / :after but the double-colon syntax is the modern standard:
a:hover { color: blue; } li:first-child { } input:focus { }
Targets an existing element in a certain state
p::before { content: "→"; } p::first-line { } input::placeholder { }
Creates a virtual element or targets a sub-part
<dialog> elements::before and ::after — Generated Content
::before and ::after insert virtual elements immediately before and
after the element's existing content. They require the content
property — even content: "" for decorative shapes. They
behave like inline elements by default but can be given any display
value.
- ✓ Feature included
- ✓ Another feature
- ✗ Not included
/* content: "" is REQUIRED — even for decorative elements */
.element::before { content: ""; } /* empty — for shapes/overlays */
.element::after { content: "→"; } /* text/emoji */
/* ── Pure CSS tooltip ── */
.tooltip { position: relative; }
.tooltip::after {
content: attr(data-tip); /* pulls from HTML attribute */
position: absolute;
bottom: calc(100% + 8px);
left: 50%;
transform: translateX(-50%);
background: #0f172a;
color: #fff;
padding: 4px 8px;
border-radius:4px;
font-size: 12px;
white-space:nowrap;
opacity: 0;
transition: opacity .2s;
}
.tooltip:hover::after { opacity: 1; }
/* ── Notification badge ── */
.nav-icon { position: relative; }
.nav-icon::after {
content: attr(data-count);
position: absolute;
top: -8px; right: -8px;
width: 18px; height: 18px;
background: #ef4444;
color: #fff;
border-radius: 50%;
font-size: 10px;
display: flex;
align-items: center;
justify-content:center;
}
/* ── Opening quote with ::before ── */
blockquote::before {
content: "\201C"; /* " unicode */
font-size: 4em;
color: rgba(38,77,228,.3);
float: left;
line-height:0.7;
margin-right:6px;
}
/* ── Required asterisk ── */
label.required::after {
content: " *";
color: #ef4444;
}
/* ── Decorative hr-style divider ── */
.divider { display: flex; align-items: center; gap: 10px; }
.divider::before, .divider::after {
content: "";
flex: 1;
height: 1px;
background:currentColor;
opacity:.3;
}
The content Property
The content property is exclusive to ::before and ::after. It accepts a wide
range of values:
"→", "✓", "\2192"./* content values */
.el::before { content: ""; } /* empty — required for shapes */
.el::before { content: "→ "; } /* text */
.el::before { content: "\2713"; } /* ✓ unicode escape */
.el::after { content: attr(data-label); } /* read HTML attribute */
.el::after { content: counter(section); }/* CSS counter value */
.el::before { content: open-quote; } /* lang-aware " */
.el::before { content: none; } /* disable pseudo-element */
/* Concatenating content values */
a[href]::after { content: " (" attr(href) ")"; }
/* renders: "Link text (https://example.com)" */
/* CSS counters with content */
body { counter-reset: section; }
h2 { counter-increment: section; }
h2::before {
content: counter(section) ". ";
color: #264de4;
}
::first-line and ::first-letter
These two target parts of text that change dynamically with the viewport — the browser recomputes which text is affected as the container resizes:
::first-line — bold first line of paragraph
This is the first line of the paragraph which gets automatically bolded by the pseudo-element — no matter how the container resizes. The remaining lines are styled normally without any extra bold weight applied.
::first-letter — magazine-style drop cap
Once upon a time, in a land far away, the developers discovered CSS pseudo-elements and their interface designs were transformed forever. The browser handles the float automatically.
/* ── ::first-line ── */
p::first-line {
font-weight: 700;
color: #0f172a;
letter-spacing:.5px;
}
/* Allowed on ::first-line:
font, color, background, text-decoration,
text-transform, letter-spacing, word-spacing,
line-height, vertical-align, clear, text-shadow */
/* ── ::first-letter — drop cap ── */
article p:first-child::first-letter {
font-size: 3.5em;
line-height:0.8;
float: left;
margin: 4px 6px 0 0;
font-weight: 800;
color: #264de4;
font-family: Georgia, serif;
}
/* Works on block/inline-block elements only.
The browser handles the text reflow automatically. */
/* Allowed on ::first-letter:
Everything ::first-line allows, plus:
font-size, float, margin, padding, border,
text-indent, vertical-align */
::selection, ::placeholder and ::marker
::selection — style text the user has highlighted. Select the text below to see it work:
Try selecting this normal text — it turns blue. This span turns orange when selected. The
custom highlight colour is applied by ::selection on the parent and the span.
::placeholder — style the placeholder text in inputs and textareas:
::marker — style the bullet or number of list items:
Unordered — custom ▸ marker
- First list item
- Second list item
- Third list item
Ordered — orange counter
- Step one
- Step two
- Step three
/* ── ::selection ── */
::selection {
background: #264de4;
color: #fff;
}
/* Limit to specific elements */
p::selection { background: #264de4; }
code::selection { background: #22c55e; color: #fff; }
/* Only color, background-color and text-shadow are allowed */
/* ── ::placeholder ── */
input::placeholder {
color: #94a3b8;
font-style: italic;
font-size: .9em;
}
/* Vendor prefixes for older browsers */
::-webkit-input-placeholder { color: #94a3b8; }
::-moz-placeholder { color: #94a3b8; }
/* ── ::marker ── */
li::marker {
color: #264de4;
font-size: 1.2em;
font-weight: 700;
}
/* Custom bullet with content */
li::marker { content: "▸ "; color: #264de4; }
li.check::marker{ content: "✓ "; color: #22c55e; }
/* Allowed on ::marker: color, font, content */
::backdrop and Modern Pseudo-elements
Modern browsers support additional pseudo-elements for newer HTML features and browser-rendered controls:
<dialog>. Style the overlay background.<video> subtitles. Style caption text colour and size./* ── ::backdrop — dialog / fullscreen overlay ── */
dialog::backdrop {
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
}
::backdrop {
background: rgba(15, 23, 42, 0.8); /* for Fullscreen API */
}
/* ── ::spelling-error ── */
::spelling-error {
text-decoration: wavy red underline;
}
/* ── ::cue — video subtitle styling ── */
::cue {
color: #fff;
background: rgba(0,0,0,.7);
font-size: 1rem;
}
/* ── ::part() — web component styling ── */
my-button::part(button) {
background: #264de4;
color: #fff;
}
/* HTML: <my-button><button part="button">... */
Common Patterns
Image overlay with ::before or ::after
/* ── Image card hover overlay ── */
.card { position: relative; overflow: hidden; }
.card::after {
content: "";
position: absolute;
inset: 0; /* shorthand for top/right/bottom/left: 0 */
background:rgba(15,23,42,.5);
opacity: 0;
transition:opacity .3s;
}
.card:hover::after { opacity: 1; }
/* ── Clearfix ── */
.clearfix::after {
content: "";
display: table;
clear: both;
}
/* ── Auto-numbered headings with counter ── */
body { counter-reset: headings; }
h2 { counter-increment: headings; }
h2::before {
content: counter(headings, decimal-leading-zero) ". ";
color: #264de4;
font-weight: 700;
}
/* ── Print URLs after links ── */
@media print {
a[href]::after { content: " (" attr(href) ")"; }
}
/* ── Triangle arrows with ::before ── */
.dropdown::after {
content: "";
display: inline-block;
border: 5px solid transparent;
border-top: 5px solid currentColor;
margin-left: 6px;
vertical-align:middle;
}
Pseudo-class vs Pseudo-element — Quick Comparison
| Feature | Pseudo-class (:) | Pseudo-element (::) |
|---|---|---|
| Syntax | Single colon : |
Double colon :: |
| What it targets | An existing element in a state | A part of an element or virtual content |
| Creates HTML? | No — selects existing | Yes — ::before/::after create virtual elements |
| In the DOM? | Element exists in DOM | ::before/::after are NOT in the DOM |
| Screen reader? | Reads the element normally | ::before/::after content is ignored by most screen readers |
| content property | Not used | Required for ::before and ::after |
| Examples | :hover, :focus, :nth-child | ::before, ::after, ::first-letter, ::selection |
Try It Yourself
Experiment with all pseudo-elements. Try changing content values, adding overlays, and styling the selection colour:
Quick Check — Chapter 35
content property must be set —
even if its value is an empty string (content: ""). Without content, the pseudo-element is not rendered at all. This is the most
common mistake when using ::before and ::after for decorative shapes — forgetting content: "".In the DOM? No. Pseudo-elements are not in the HTML DOM. This means:
— You cannot select them with JavaScript (
document.querySelector
won't find them)— You cannot add event listeners to them
— Their content is generally not read by screen readers
— Therefore they should only be used for decorative content — never for meaningful information that users need to access
They are positioned "virtually" relative to their parent element. They can be positioned absolutely or relatively, given dimensions, backgrounds, borders, and any CSS that a real element can have (except they can't contain HTML child elements).
content: "→" or content: "\2713" (unicode escape for ✓) — inserts literal textEmpty:
content: "" — required for decorative shapes
and overlays. No visible text.attr():
content: attr(data-label) — reads the value
of an HTML attribute. Useful for tooltips (reading data-tip) and print styles (showing hrefs).counter():
content: counter(section) — outputs the
current CSS counter value. Used for auto-numbered headings and custom list counters.url():
content: url("icon.svg") — inserts an image
(rarely used — background-image gives better control).none:
content: none — disables the pseudo-element.
Useful to reset an inherited rule.open-quote / close-quote:
content: open-quote —
inserts the language-appropriate opening quote character.Values can be concatenated:
content: "URL: " attr(href) " →"
::selection — very restricted. Only three
properties work:—
color—
background-color (or background)—
text-shadowWidth, padding, border, font properties — none of these apply to
::selection.::marker — also restricted but slightly more
flexible:—
color—
font (all font sub-properties)—
content — lets you replace the bullet with custom
text/emoji/symbol—
unicode-bidi, direction, white-spaceThe
content property on ::marker
is what makes it powerful — li::marker { content: "▸ " } completely
replaces the default bullet.
position: relative on the parent and position: absolute on the ::after,
with opacity transition:1. Add a
data-tip attribute to the HTML element with the tooltip
text2. Set
position: relative on the element3. On
::after: content: attr(data-tip), position: absolute, positioned above (bottom: calc(100% + 8px)), opacity: 0, transition: opacity .2s4. On
:hover::after: opacity: 1Using
content: attr(data-tip) reads the tooltip text directly from
the HTML attribute — this way you don't need to hardcode it in CSS and can have different tooltips per
element.Accessibility note: CSS tooltips created this way are not accessible to screen readers or keyboard users. For accessible tooltips, use the
title attribute or a proper
ARIA tooltip widget with JavaScript.
Manual
<span> approach:— Requires wrapping every first letter in HTML:
<span class="drop-cap">O</span>nce upon...— Adds presentational HTML — mixing structure with appearance
— Must be applied to every paragraph individually
— Easy to forget or get wrong in CMS-generated content
::first-letter approach:— Pure CSS — no HTML changes needed:
p::first-letter { font-size: 3em; float: left; }— Automatically applies to any element matching the selector
— The browser determines which is the "first letter" — handles punctuation, quotes, and other leading characters correctly
— Keeps HTML semantic and clean
— Can be targeted precisely:
article p:first-child::first-letter
only affects the opening paragraphAlways prefer
::first-letter over manual spans for typographic
effects. Reserve spans for semantic markup needs.
::before
or ::after to be visible?content value reads from an HTML
attribute?<dialog> element?::marker to
replace the default bullet with a custom symbol?::before or ::after content?- Pseudo-element (
::) — creates a virtual element or targets a sub-part of an element. Different from pseudo-class (:) which targets states. ::beforeand::after— requirecontentproperty. Not in the DOM. Used for decorative shapes, tooltips, badges, dividers, quotes, and overlays.contentvalues:""(empty),"text",attr(x),counter(n),open-quote,none. Can be concatenated.- Accessibility: pseudo-element content is not accessible to screen readers. Never put
meaningful content in
::before/::after. ::first-line— styles the first rendered line of a block. Recomputes on resize. Allowed: font, color, text-decoration, letter-spacing.::first-letter— drop cap styling. Also supports float, margin, padding, border. Must be on a block element.::selection— custom highlight colour. Onlycolor,background-color,text-shadowallowed.::placeholder— style input/textarea placeholder text. Use vendor prefix::-webkit-input-placeholderfor older browsers.::marker— style list bullet/counter. Usecontenton ::marker to replace the bullet symbol. Allowed: color, font, content.::backdrop— style the overlay behind<dialog>and fullscreen elements.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.