CSS Pseudo-classes
Pseudo-classes select elements based on their state or position — :hover, :focus, :first-child, :last-child, :active. They let you style elements dynamically without JavaScript.
Common Pseudo-classes
- :hover — Mouse is over the element. The most common interactive pseudo-class
- :focus — Element has keyboard focus (clicked or tabbed to). Essential for accessibility
- :active — Element is being clicked/pressed. Used for button press effects
- :first-child / :last-child — First or last child of its parent
- :nth-child(n) — Select by position: :nth-child(2) = second child, :nth-child(odd) = all odd children
- :not(selector) — Exclude elements: p:not(.special) selects all <p> except those with class 'special'
- :focus-visible — Focus ring only for keyboard users (not mouse clicks). Modern accessibility standard
Pseudo-classes Code
/* Interactive states */
a:hover { color: #E44D26; }
a:focus-visible { outline: 2px solid #667eea; outline-offset: 2px; }
button:active { transform: scale(0.95); }
/* Positional */
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
tr:nth-child(even) { background: #f8f9fa; }
/* Negation */
p:not(:last-child) { margin-bottom: 1em; }
.nav-link:not(.active) { opacity: 0.7; }Tip
Use :focus-visible instead of :focus for focus rings. :focus fires on mouse clicks too (showing an unwanted outline), while :focus-visible only fires for keyboard navigation — the modern standard.
Selectors target HTML elements for styling
Common Mistake
Removing :focus outlines globally with *:focus { outline: none }. This breaks keyboard navigation. Use :focus:not(:focus-visible) { outline: none } instead to preserve keyboard focus indicators.
Practice Task
Build an accessible nav bar: (1) :hover color change on links, (2) :focus-visible outline for keyboard users, (3) :active scale(0.95) for click feedback, (4) .active class with :not(.active) styling the rest.
Quick Quiz
Key Takeaways
- Pseudo-classes select elements based on their state or position — :hover, :focus, :first-child, :last-child, :active.
- :hover — Mouse is over the element. The most common interactive pseudo-class
- :focus — Element has keyboard focus (clicked or tabbed to). Essential for accessibility
- :active — Element is being clicked/pressed. Used for button press effects