CSS Pseudo-class
A pseudo-class selects elements that are in a particular state — being hovered, focused, the first child, valid, etc. They start with a single colon.
Pseudo-classes you'll use weekly
| Selector | Matches | Example use |
|---|---|---|
:hover | Mouse is over the element. | Button highlight. |
:focus | Element has keyboard focus. | Accessible form outlines. |
:focus-visible | Focus from keyboard only (not mouse click). | Outlines that don't bother mouse users. |
:active | Element is being pressed. | Button "down" effect. |
:disabled | Form control is disabled. | Greyed-out state. |
:checked | Checkbox or radio is on. | Custom switches. |
:first-child | Element is the first child of its parent. | Remove the top border of a list. |
:last-child | Element is the last child. | Drop the trailing margin. |
:nth-child(n) | Match by index — supports formulas like 2n, 3n+1. | Zebra-striped tables. |
:not(...) | Anything that does not match the inner selector. | Style all buttons except disabled ones. |
:is(...) / :where(...) | Grouping with shared specificity. | DRY up long selector lists. |
Link states in order
For links specifically, the order matters because each state overrides the last:
LoVe HAte
a:link { color: #2965F1; } /* never visited */
a:visited { color: #6f42c1; } /* already visited */
a:hover { color: #04AA6D; } /* mouse is over it */
a:active { color: #E44D26; } /* being clicked */
Tip: Pseudo-classes start with
: (state). Pseudo-elements start with :: (a part of an element, like ::before). Same vocabulary, different colons.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Pseudo-class</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Change the button colour while the mouse is over it.
.btn
{ background: #04AA6D; }
A single colon, then the state name.
Discussion
Loading…