Pseudo-classes

Style elements in a special state like hover or first-child.

Syntaxa:hover { } li:nth-child(2) { }

A pseudo-class targets elements in a particular state, written with a single colon.

  • :hover — the mouse is over the element.
  • :focus — the element is focused.
  • :first-child / :last-child — position among siblings.
  • :nth-child(n) — matches by index or formula.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A designer uses :hover to highlight navigation links with an underline when the user moves the mouse over them.
  • A developer uses :nth-child(even) on table rows to apply a zebra-stripe background without adding classes to each row.
  • A form validation style uses :invalid to show a red border on inputs that fail browser-native validation before submission.

More examples

Hover state on a button

Uses :hover to darken the button background when the user points to it, providing clear interactive feedback.

Example · css
.btn {
  background-color: #2965f1;
  color: #fff;
  padding: 8px 18px;
  border: none;
  cursor: pointer;
}
.btn:hover {
  background-color: #1a4fbf;
}

Zebra striping with nth-child

Applies alternating row colors to a table using :nth-child(even/odd) without any HTML classes.

Example · css
tr:nth-child(even) {
  background-color: #f4f7ff;
}
tr:nth-child(odd) {
  background-color: #fff;
}

Form field validation states

Combines :focus, :valid, and :invalid pseudo-classes to give form fields visual feedback for interaction and validation state.

Example · css
input:focus {
  outline: 2px solid #2965f1;
}
input:valid {
  border-color: #27ae60;
}
input:invalid {
  border-color: #c0392b;
}

Discussion

  • Be the first to comment on this lesson.
Pseudo-classes — CSS | SoundsCode