Course outline · 0% complete

0/30 lessons0%

Course overview →

States: hover, focus, and pseudo-classes

lesson 4-4 · ~9 min · 13/30

Styling states, not just elements

Every polished interface responds before any JavaScript runs: buttons highlight under the cursor, links change once visited, inputs glow when selected. If controls gave no feedback, users could not tell what is clickable — so browsers track each element's current state, and CSS can select on it.

A pseudo-class is a selector suffix, written with a colon, that matches an element only while it is in a given state:

a:hover { color: darkgoldenrod; }     /* cursor is over it */
button:active { background: gray; }   /* being pressed right now */
input:focus { border-color: black; }  /* selected for typing */
a:visited { color: purple; }          /* already followed */

a:hover still scores as one type + one class-level part in the lesson 4-3 specificity math, so (0,1,1) — pseudo-classes count in the classes bucket.

focus is not optional

:hover is cosmetic. :focus is accessibility. Keyboard users move through a page with the Tab key, and the focus outline — the ring the browser draws around the focused control — is the only way they can see where they are. Remove it and the page becomes unusable without a mouse.

The rule working teams follow: never write outline: none unless you replace it with an equally visible focus style in the same rule:

button:focus {
  outline: 2px solid #d4af37;  /* replaced, not removed */
  outline-offset: 2px;
}

Two structural pseudo-classes round out the daily set — they select by position, not state:

li:first-child { font-weight: bold; }   /* first li in its parent */
tr:nth-child(even) { background: #eee; } /* zebra-striped table rows */

Quiz

A user is tabbing through your form with the keyboard. Which pseudo-class matches the input they land on?

Give the button real states in the CSS pane: 1) a .cta:hover rule that changes the background to black and the color to #d4af37, 2) a .cta:focus rule with outline: 3px solid black and outline-offset: 2px. Hover the button, then click into the preview and press Tab to see the focus style.

Problem

Which pseudo-class applies only while the user's cursor is over the element?