Pseudo-Classes: :hover, :focus-visible, :nth-child() and More

Pseudo-classes select elements by their state, such as hovered, focused, checked or disabled, or by their position, such as first, last or every other, :not() leaves some out, and link states go in the order :link, :visited, :hover, :focus, :active.

Apprentice · CSS · Updated

By

After this lesson you can

  • Style an element's state with :hover, :focus-visible, :checked and :disabled, keeping a visible focus for keyboard users
  • Pick elements by position with :first-child, :last-child and :nth-child(), and leave some out with :not()
  • Style links with :link, :visited, :hover, :focus and :active, written in that order, and explain why the order matters

Key takeaways

  • A pseudo-class starts with a colon and adds a condition to a selector, such as li:hover, read "li when hovered".
  • :hover, :active, :focus, :checked and :disabled match an element's state. Link rules go in the order :link, :visited, :hover, :focus, :active, because the later rule wins a tie.
  • People using a keyboard see where they are only by the focus outline. Never remove it without putting a clear :focus-visible style in its place.
  • :first-child, :last-child and :nth-child() pick elements by position. :nth-child(odd) stripes rows, and :nth-child(3n) reaches every third.
  • :not() leaves elements out, as in li:not(:last-child): every song but the last.

Think of any music app. A song lights up when your pointer moves over it, the rows alternate shades so your eye can follow them, the heart turns red when you like a song, and a button goes gray when it can't be used yet. None of that is written in the HTML: the HTML has no idea where your pointer is. Pseudo-classes let CSS react to what's happening on the page, and to where an element sits in a list. You'll use them on every site you ever style.

A colon means "when"

A pseudo-class is a word after a colon (:) that adds a condition to a selector. li:hover is read "li when hovered": a list item, but only while the pointer is over it. Pseudo means "not quite": it works like a class, but nobody wrote it into the HTML. The browser adds and removes it as things change.

Here are two songs from the Road Trip Mix page, the playlist this chapter styles, plus the Share button from its footer:

<ol>
  <li>
    <strong>Golden Hour Highway</strong>
    <span>Juniper &amp; the Jets</span>
    <input type="checkbox" aria-label="Like Golden Hour Highway">
  </li>
  <li>
    <strong>Windows Down</strong>
    <span>Maple Avenue</span>
    <input type="checkbox" aria-label="Like Windows Down" checked>
  </li>
</ol>
<button disabled>Share this mix</button>

Two attributes may be new: checked starts a checkbox ticked, and disabled switches a button off. Each is written on its own, with no value.

The pointer: :hover and :active

  • :hover matches while the pointer is over the element.
  • :active matches while it's being pressed: the moment between the mouse button going down and coming up.
li:hover {
  background-color: #e0f2fe;
}

button:active {
  background-color: #1e3a8a;
}

The song under the pointer turns light blue, and the button goes a darker blue while it's pressed, so it feels pushed. Phones and tablets have no pointer to hover with, so never hide something people need behind :hover alone. Links have one more state, :visited, for a link the person has already opened. For privacy, browsers let it change only colors.

The keyboard: :focus and :focus-visible

Many people move through a page with the Tab key instead of a mouse: people who can't hold a mouse steady, people who are blind and use a screen reader, and plenty of fast typists. The element that Tab has landed on has focus, and browsers draw an outline around it. That outline is the only way a keyboard user knows where they are, like the cursor when you type.

  • :focus matches the element that has focus, however it got there: Tab, a click or a tap.
  • :focus-visible matches it only when the browser thinks an outline helps, mainly when focus came from the keyboard. Clicking a button with a mouse doesn't trigger it, which is why designers like it.
input:focus-visible,
button:focus-visible {
  outline: 3px solid #1d4ed8;
  outline-offset: 2px;
}

outline-offset moves the outline 2 pixels out from the edge, so it doesn't touch the box. You'll find outline: none; in many stylesheets, written because someone disliked the default outline. Without a replacement, keyboard users are lost. If you change the outline, change it to something at least as clear, and check by pressing Tab through the page yourself. Accessibility guidelines (WCAG, as a class may call them) require a visible focus.

Try it. Open any site you use and press Tab a few times. Can you always see where you are? Then add the rule above to your road-trip.css and Tab through your playlist's checkboxes.

Styling links: :link, :visited, :hover, :focus, :active, in that order

Each song title on Road Trip Mix links to its band's page, and the owner wants the links to say what's going on: blue for a band you haven't opened yet, purple for one you have, orange while your pointer is on it or the keyboard has landed on it, and red while it's being pressed. Here's a first try:

a:hover {
  color: #c2410c;
}

a:link {
  color: #1d4ed8;
}

a:visited {
  color: #7c3aed;
}

Hover over a link and nothing happens: it stays blue, or purple if you've opened it. Every one of these selectors scores the same (one element and one pseudo-class, as Specificity: Scoring a Selector counts them), so when two of them match the same link, the cascade's last tiebreaker decides: the rule written later wins. A link you've never opened, with the pointer on it, matches both a:hover and a:link, and a:link comes later, so blue wins.

Links have five states, and one link can be in several at once. The first one is new: :link, read "link", matches a link (an <a> with an href) that the person hasn't visited yet. So every link is either :link or :visited, and on top of that it may be hovered, focused or pressed. Write the rules from the calmest state to the busiest, so the busier one comes later and wins:

a:link {
  color: #1d4ed8;
}

a:visited {
  color: #7c3aed;
}

a:hover,
a:focus {
  color: #c2410c;
}

a:active {
  color: #be123c;
}

Now a link you've opened, with the pointer on it, matches a:visited and a:hover, and a:hover comes later: orange. Press it, and a:active, last of all, turns it red. :focus sits beside :hover so a keyboard user gets the same signal a mouse user does (:focus-visible works in its place, as in the section above).

The order is :link, :visited, :hover, :focus, :active. One way to remember the first letters, L V H F A: "Lord Vader's Handle Formerly Anakin."

Try it. In road-trip.css, wrap a song title in <a href="https://example.com"> and add the five rules in the wrong order (a:hover first). Hover, then move a:hover and a:focus down below a:visited and hover again.

Forms: :checked and :disabled

  • :checked matches a checkbox or radio button that's ticked, and changes the moment someone clicks it.
  • :disabled matches a form control that's switched off. :enabled is its opposite.
input:checked {
  accent-color: #e63973;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

A liked song's checkbox turns pink (accent-color colors a checkbox's tick and box), and the Share button looks unavailable, with a "no" sign as the pointer. The fading comes from opacity, which makes a whole element see-through, everything inside it included: 1 is solid, 0 is invisible, and 0.5 is halfway, so the page behind shows through the button. Finishing Touches: Rounded Corners, Shadows and Gradients in Module 5 uses it again for softer designs. Pair :checked with the combinators from Combinators: Descendant, Child and Sibling and the click can change other elements: input:checked + span reaches the span right after a ticked box.

Position: :first-child, :last-child and :nth-child()

The next pseudo-classes don't change: they depend on where an element sits among its siblings.

  • :first-child and :last-child match the first and the last child of a parent.
  • :nth-child(), read "nth child", matches by number. Inside the parentheses go odd (1, 3, 5…), even (2, 4, 6…), one number (:nth-child(4), the fourth), or a pattern such as 3n (every third: 3, 6, 9, 12). In a pattern, n counts 0, 1, 2, 3… so 3n gives 0, 3, 6, 9…, and there is no zeroth child. 2n+1 is another way to write odd.
li:nth-child(even) {
  background-color: #f1f5f9;
}

li:first-child strong {
  font-size: 1.25rem;
}

Every second song gets a light gray stripe, like the rows of a printed bank statement, and the first song's title is bigger. Add a song to the middle of the list and the stripes stay correct, since the browser counts again. One catch: :nth-child() counts every child, whatever its type. In a song, span:nth-child(2) is the artist, since the <strong> is child 1.

Leaving some out: :not()

:not(), read "not", matches everything its parentheses don't. li:not(:last-child) is "every song except the last":

li:not(:last-child) {
  border-bottom: 1px solid #cbd5e1;
}

That draws a line between songs, with no stray line under the last one. Without :not(), you'd write a border for every song, then a second rule to take it off the last one.

The playlist with every second row striped, the hovered row light blue, a liked song's checkbox pink, and a thick blue focus outline around the checkbox that keyboard focus is on

Do it: make the playlist easy to follow

On a phone in a moving car, Road Trip Mix's rows blur together, nobody can tell which songs they've liked, and a friend who uses the keyboard loses track of which heart they're on. On this version of the page, each song's Like checkbox comes first, before its title. The mix's owner asks for:

  • A light gray stripe, #f1f5f9, on the first song, the third, the fifth and so on. The songs in between stay white.
  • A liked song's title in pink, #e63973, the moment its box is ticked. The other titles stay black.
  • A clear outline on a checkbox the keyboard lands on: 3px solid #1d4ed8.

Practiced live on the lesson page: write the CSS right there and check it.

Do it: color the band links so every state shows

Each song on Road Trip Mix now links to its band's page. The owner wants the links to tell people where they've been and what they're touching, and every color has to show up when it should:

  • A band page you haven't opened yet: blue, #1d4ed8.
  • A band page you've already opened: purple, #7c3aed.
  • While the pointer is on a link, or the keyboard has landed on it: orange, #c2410c.
  • While a link is being pressed: red, #be123c.
  • In the order that lets every color win when it should: the not-yet-opened rule first, then opened, then pointer and keyboard, then pressed last.

Practiced live on the lesson page: write the CSS right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Pseudo-classes make a page respond to the people using it, and they keep long lists readable without a class on every row. Keep the focus visible, and the page works for everyone who can't or doesn't use a mouse.

Key terms

Cheat sheets

Related