Pseudo-classes
Style elements in a special state like hover or first-child.
Syntax
a: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
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.
.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.
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.
input:focus {
outline: 2px solid #2965f1;
}
input:valid {
border-color: #27ae60;
}
input:invalid {
border-color: #c0392b;
}
Discussion