What are pseudo-classes and pseudo-elements? Give examples.

LowIntermediateCss
Preparing for interviews?

Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.

Quick Answer

Pseudo-classes and pseudo-elements extend CSS selectors to style elements based on state or to create virtual elements that do not exist directly in the DOM. They enable powerful interactions, dynamic states, and content generation without additional markup.

Answer

Overview

Pseudo-classes and pseudo-elements allow developers to target special states or parts of elements beyond basic selectors. A pseudo-class represents a state (like hover or focus), while a pseudo-element targets a portion of content (like the first line or a generated content block).

Feature

Syntax

Purpose

Pseudo-class

selector:state

Targets elements based on user interaction or state.

Pseudo-element

selector::part

Selects a specific portion of an element or generates virtual content.

Pseudo-class vs Pseudo-element overview

Common Pseudo-Classes

CSS
a:hover {
  color: #0ea5e9;
}
input:focus {
  border-color: #2563eb;
}
li:first-child {
  font-weight: bold;
}
                  

These respond dynamically to user actions — hover changes color, focus highlights inputs, and first-child styles specific items in a list.

Common Pseudo-Elements

CSS
p::first-line {
  font-weight: bold;
}
p::before {
  content: '💡 Note: ';
  color: #f59e0b;
}
p::after {
  content: ' ✔';
  color: #16a34a;
}
                  

Pseudo-elements allow inserting generated content, emphasizing specific portions, or enhancing UX without modifying HTML.

Notable Differences

      • Pseudo-classes use a single colon (:), e.g. :hover.
      • Pseudo-elements use a double colon (::) to distinguish structural parts, e.g. ::before.
      • They can be combined — for instance: a:hover::after adds content only when hovered.

Practical Applications

      • Creating tooltips with ::after and content.
      • Animating buttons on :hover or :active.
      • Styling dynamic elements in forms and navigation bars.

Still so complicated?

Think of pseudo-classes as describing when an element behaves differently, and pseudo-elements as describing which part of it you’re styling or creating.

Summary
      • Pseudo-classes define element states (e.g., :hover, :focus).
      • Pseudo-elements define virtual parts (e.g., ::before, ::after).
      • Use them to enhance interactivity and add decorative content without extra HTML.
Similar questions
Guides
16 / 30