Lesson

CSS Pseudo-class

10 min reading
Free Course

CSS Pseudo-Classes: Styling Element States and Structure

A CSS pseudo-class starts with a single colon (:) and matches an element based on its live state, user interaction, form validity, or position among siblings—without adding extra HTML classes or JavaScript event listeners.

High-Value Pseudo-Classes You Will Use Daily

  • Interaction States: :hover (pointer over element), :focus-visible (keyboard Tab focus), :active (while pressed).
  • Structural Matching: :first-child, :last-child, :nth-child(even), and :nth-child(3n).
  • Form States: :checked (checked checkboxes/radios), :disabled, :valid, :invalid, and :placeholder-shown.
  • Logical Helpers: :not(.excluded) skips specific elements, and :is(h1, h2, h3) groups selectors concisely.
.nav-item:not(:last-child) {
    border-bottom: 1px solid #e2e8f0;
}

.input-field:focus-visible {
    outline: 2px solid #2563eb;
    outline-offset: 2px;
}

/* Highlight invalid input only after user starts typing */
.input-field:not(:placeholder-shown):invalid {
    border-color: #dc2626;
}

.feature-row:nth-child(odd) {
    background-color: #f8fafc;
}

Careful with :invalid on Fresh Forms

Applying :invalid alone turns required fields red the instant a blank form loads, frustrating visitors before they type a single letter. Combining :not(:placeholder-shown):invalid (or modern :user-invalid) waits until the visitor actually enters bad data.

Common Mistakes to Avoid

  • Confusing :first-child with :first-of-type: p:first-child matches only if p is the very first child inside its parent; if an h2 comes first, p:first-child matches nothing—use p:first-of-type instead.
  • Relying on :hover for essential hidden content: Touch devices have no hover state, so keep critical menus and tooltips clickable too.
  • Forgetting that :nth-child() is 1-indexed: Unlike JavaScript arrays, :nth-child(1) selects the first element, not 0.

Frequently Asked Questions

What is the difference between :is() and :where()?

Both shorten grouped selectors like :is(section, article) h2, but :is() takes the highest specificity inside its argument list while :where() always has zero specificity for easy overrides.

Can I combine multiple pseudo-classes on one selector?

Yes. Chaining states like button:not(:disabled):hover applies hover effects strictly to enabled buttons.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Lesson Recap Quiz Available

Test Your Knowledge

You've completed this section! Take a quick 5-question quiz to check your understanding.

CSS Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum