Tutorials CSS Pseudo-elements
Ch 35 / 60
Chapter 35 Intermediate 9 min read CSS

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.

What you'll learn
Pseudo-element syntax (:: vs :)
::before and ::after — content injection
The content property — all values
::first-line and ::first-letter
::selection, ::placeholder, ::marker
::backdrop, ::spelling-error, modern pseudo-elements

Pseudo-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:

Pseudo-class — targets a STATE
a:hover  { color: blue; }
li:first-child { }
input:focus { }

Targets an existing element in a certain state

Pseudo-element — targets a PART or creates content
p::before  { content: "→"; }
p::first-line { }
input::placeholder { }

Creates a virtual element or targets a sub-part

::before
Insert generated content before element's content
::after
Insert generated content after element's content
::first-line
First rendered line of a block element
::first-letter
First letter of a block element. Used for drop caps.
::selection
User-selected (highlighted) text
::placeholder
Placeholder text in input/textarea
::marker
Bullet or counter of a list item
::backdrop
Background behind fullscreen or <dialog> elements

::before and ::after — Generated Content

Content Generation

::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.

Pure CSS tooltip with ::after
Hover me for tooltip
Notification badge with ::after
🔔 Notifications
Opening quote mark with ::before
Design is not just what it looks like. Design is how it works.
Decorative divider with ::before + ::after
Section Title
OR
Required field asterisk with ::after
Email address
Full name
Phone (optional)
Icon/emoji prefix with ::before
  • ✓ Feature included
  • ✓ Another feature
  • ✗ Not included
CSS — ::before and ::after
/* 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:

content: ""
Empty string — pseudo-element is rendered but invisible. Use for decorative shapes.
content: "text"
Literal text or unicode characters: "→", "✓", "\2192".
content: attr(x)
Reads the value of attribute x from the HTML element. Useful for tooltips and data labels.
content: counter(n)
Outputs the value of a CSS counter. Used for auto-numbered headings, lists.
content: url("img")
Inserts an image. Less common — use background-image instead for better control.
content: none
Disables the pseudo-element entirely. Useful to override an inherited or base rule.
content: normal
Default. On ::before/::after it acts like none (no pseudo-element rendered).
content: open-quote
Inserts the language-appropriate opening quotation mark.
CSS — content property values
/* 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

Typography

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.

CSS — ::first-line and ::first-letter
/* ── ::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

UI Pseudo-elements

::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

  1. Step one
  2. Step two
  3. Step three
CSS — ::selection, ::placeholder, ::marker
/* ── ::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:

::backdrop
Background layer behind fullscreen elements and <dialog>. Style the overlay background.
::spelling-error
Text flagged by the browser's spell checker. Style the underline colour/style.
::grammar-error
Text flagged by the browser's grammar checker.
::cue
WebVTT cues in <video> subtitles. Style caption text colour and size.
::part()
Style named parts of web components from outside the shadow DOM.
::slotted()
Style slotted content in a web component shadow DOM.
CSS — ::backdrop and modern pseudo-elements
/* ── ::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 (no overlay)
Overlay via ::after (hover)
CSS — Common ::before / ::after patterns
/* ── 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
Free Resource
CSS3 Cheat Sheet — All Properties & Selectors
Complete reference covering all CSS pseudo-elements and pseudo-classes with examples.
Download PDF

Try It Yourself

Experiment with all pseudo-elements. Try changing content values, adding overlays, and styling the selection colour:

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js with real projects and placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools

Quick Check — Chapter 35

Questions & Answers
Requirement: The 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).
String: content: "→" or content: "\2713" (unicode escape for ✓) — inserts literal text

Empty: 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-shadow

Width, 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-space

The content property on ::marker is what makes it powerful — li::marker { content: "▸ " } completely replaces the default bullet.
The pattern uses 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 text
2. Set position: relative on the element
3. On ::after: content: attr(data-tip), position: absolute, positioned above (bottom: calc(100% + 8px)), opacity: 0, transition: opacity .2s
4. On :hover::after: opacity: 1

Using 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.
Both achieve similar visual results, but they differ significantly in implementation and maintenance:

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 paragraph

Always prefer ::first-letter over manual spans for typographic effects. Reserve spans for semantic markup needs.
Multiple Choice Questions
Question 1 of 5
What is the minimum requirement for ::before or ::after to be visible?
Question 2 of 5
Which content value reads from an HTML attribute?
Question 3 of 5
Which pseudo-element should you use to style the background behind a <dialog> element?
Question 4 of 5
Which CSS property can you set on ::marker to replace the default bullet with a custom symbol?
Question 5 of 5
Why should meaningful text never be placed in ::before or ::after content?
Chapter Summary
  • Pseudo-element (::) — creates a virtual element or targets a sub-part of an element. Different from pseudo-class (:) which targets states.
  • ::before and ::after — require content property. Not in the DOM. Used for decorative shapes, tooltips, badges, dividers, quotes, and overlays.
  • content values: "" (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. Only color, background-color, text-shadow allowed.
  • ::placeholder — style input/textarea placeholder text. Use vendor prefix ::-webkit-input-placeholder for older browsers.
  • ::marker — style list bullet/counter. Use content on ::marker to replace the bullet symbol. Allowed: color, font, content.
  • ::backdrop — style the overlay behind <dialog> and fullscreen elements.
~9 min read
Intermediate level
Chapter 35 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel