CSS3
CSS3

Pseudo-classes & Pseudo-elements

A pseudo-class targets an element based on its STATE or POSITION, without needing any extra class or id in your HTML. :hover applies styling only while the mouse is over an element the classic way to make a button visibly react to a cursor. :focus applies while an element (usually a form input) is actively selected/clicked into, important for accessibility so keyboard users can see where they are. :nth-child(2) targets only the 2nd child of its parent useful for striping table rows (:nth-child(odd) / :nth-child(even)) without adding a class to every single row. Pseudo-ELEMENTS are different: they let you style or insert a specific PART of an element that doesn't otherwise exist as its own tag. ::before and ::after insert generated content right before or after an element's real content commonly used for decorative icons, quote marks, or little arrow indicators using content: '→' inside the rule. Note the syntax difference: pseudo-classes use one colon (:hover), pseudo-elements use two (::before).

Why this matters

  • ·:hover and :focus add interactivity feedback with zero JavaScript
  • ·:nth-child styles patterns like striped rows without extra HTML classes
  • ·::before/::after add decorative content without cluttering the HTML

Common mistakes

  • ·Forgetting :focus styles can make a site unusable for keyboard-only users
  • ·Confusing single colon (pseudo-class) with double colon (pseudo-element) syntax can silently fail in strict setups
  • ·Overusing ::before/::after content for real information (not decoration) hides it from screen readers
Your code
Live preview

Frequently asked questions

No the style attribute can only style the base state. :hover and other pseudo-classes require internal or external CSS rules.

Practice questions

Question 1

Add a :hover rule that changes a button's background color, using the internal method.

Your code
Live preview

Question 2

Stripe a list's alternating items using :nth-child(even).

Your code
Live preview

Quick check

Just for this topic answer honestly, then check yourself.

1 / 10

Which pseudo-class applies while the mouse is over an element?