Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / CSS Tutorial / Chapter 5: Advanced Selectors, Effects & Variables
CSS ⏱ 10 min read

Pseudo-elements (::before, ::after)

Pseudo-elements let you insert decorative graphics, icons, and layout embellishments without cluttering your HTML markup.

What is it?

A pseudo-element is a keyword added to a selector preceded by two colons `::` that lets you style a specific part of an element or create virtual child elements (`::before` and `::after`).

Why is it used?

Generates decorative accents, breadcrumb separators, custom bullet icons, tooltips, and badges purely in CSS.

Detailed Explanation

The most widely used pseudo-elements are `::before` and `::after`. Rules for `::before` and `::after`: 1. Must include the `content: ''` property (even if empty string `''`). Without `content`, the pseudo-element will not render! 2. They render as inline elements by default unless you declare `display: block` or `display: inline-block`. Other pseudo-elements include `::selection` (styles highlighted text) and `::placeholder` (styles input placeholder text).

Syntax Structure

Syntax Blueprint
selector::before {
  content: '';
  display: inline-block;
  /* styles */
}

Code Example

CSS Code
/* Breadcrumb Separator with ::after */
.breadcrumb-item + .breadcrumb-item::before {
  content: '/';
  margin: 0 8px;
  color: #5f5f5d;
}

/* Custom Section Eyebrow with decorative dot */
.section-eyebrow {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  font-weight: 700;
  text-transform: uppercase;
  color: #1c1c1c;
}

.section-eyebrow::before {
  content: '';
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #1c1c1c;
}

/* Text Selection Color */
::selection {
  background-color: #1c1c1c;
  color: #fcfbf8;
}

Explanation of the Code

• `::before` inserts a dark decorative circular dot before the eyebrow label. • `::selection` customizes text highlight color to match institute branding.

Expected Output

Clean breadcrumb slashes generated automatically, decorative category badges, and branded text selection highlight.

Real-World Application

Design systems use `::before` and `::after` for tooltips, badge notification dots, and gradient underline animations.

Common Mistakes to Avoid

• Forgetting the `content: ""` property, causing the pseudo-element to remain completely invisible. • Attempting to use `::before` or `::after` on void elements like `<img>` or `<input>` (they cannot have child elements).

Quick Practice Challenge

Add a checkmark (✓) before every list item in a `.feature-list` class using `::before`.

Key Takeaways

• Always set `content: ''` when creating `::before` or `::after`. • Keep decorative elements in CSS instead of polluting HTML markup. • Use `::selection` to customize user highlight colors.