Skip to content
Back to Concepts
CSS UniverseCurriculumPseudo-Classes & Elements
1st Year CS & Web Engineering FoundationCore Concept 03

Pseudo-Classes & Elements

Bring your interfaces to life without JavaScript! Style dynamic user states (hover, focus, active), target structural positions (:nth-child), and inject decorative virtual sub-elements (::before, ::after).

1. The Mental Model

Moods vs Accessories

The difference between a pseudo-class and a pseudo-element is simple:

:pseudo-class (Single Colon) = The Mood/State

Describes the temporary condition or structural role of an existing element. The element didn't change; its mood changed!

button:hover { transform: translateY(-2px); }
Specificity contribution: (0, 0, 1, 0) — Same as 1 Class!

::pseudo-element (Double Colon) = The Accessory

Creates or targets an invisible virtual sub-element. Like putting a hat (::before) or backpack (::after) on an element without writing extra HTML tags!

.badge::before { content: "★"; margin-right: 4px; }
Specificity contribution: (0, 0, 0, 1) — Same as 1 Element tag!
2. Interaction States & The LVHA Rule

Why Does Link Hover Sometimes Fail? (The LVHA Order)

All link pseudo-classes have identical specificity (0, 0, 1, 0). If written in the wrong source order in your stylesheet, an active or visited style can permanently block hover effects!

1. :link

Unvisited links.

2. :visited

Already clicked in history.

3. :hover

Mouse cursor over link.

4. :active

Mouse button pressed down.

Memory Mnemonic: Remember L-o-V-e H-A-t-e (Link, Visited, Hover, Active). Always write them in this order!
3. Interactive :nth-child(An + B) Sandbox

Master the An + B Math Formula

The :nth-child(An + B) formula matches elements in cycles: A is cycle size, B is starting offset. Try typing any formula or picking a preset:

Presets:
10 DOM Child Nodes <li>:
Item#1MATCH
Item#2—
Item#3MATCH
Item#4—
Item#5MATCH
Item#6—
Item#7MATCH
Item#8—
Item#9MATCH
Item#10—
4. Virtual Elements Studio (::before & ::after)

Injecting Icons & Badges Without Extra HTML

The #1 rule of ::before and ::after: They MUST have content: ""! Without the content property, browsers will not generate the pseudo-element at all.

New::after
HTML remains clean: <span class="badge">New</span>
5. Common Traps & Pro-Tips

The Infamous `:first-child` Trap

Why does `p:first-child` match nothing when an `<h1>` is present?

p:first-child does NOT mean "find the first paragraph inside the div". It means "Is this element a paragraph AND is it the very first child of its parent?"

<div class="article">
<h1>Title</h1> <-- Child #1
<p>Paragraph 1</p> <-- Child #2 (p:first-child FAILS!)
</div>
Fix: Use p:first-of-type! It specifically scans for the first <p> element regardless of preceding headings!
Next Concept in Curriculum

4. :is(), :where(), and :has()

Modern relational parent selectors and zero-specificity baseline reset functions.

Continue to Modern Selectors