iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

SelectorMatchesExample use
:hoverMouse is over the element.Button highlight.
:focusElement has keyboard focus.Accessible form outlines.
:focus-visibleFocus from keyboard only (not mouse click).Outlines that don't bother mouse users.
:activeElement is being pressed.Button "down" effect.
:disabledForm control is disabled.Greyed-out state.
:checkedCheckbox or radio is on.Custom switches.
:first-childElement is the first child of its parent.Remove the top border of a list.
:last-childElement 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 &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Change the button colour while the mouse is over it.

.btn { background: #04AA6D; }

Test yourself

Q1. Which selector styles a link only while the mouse is over it?
Q2. In the "LoVe HAte" mnemonic, which order should the link states appear?
Q3. Pseudo-classes are written with one colon. What does a double-colon mark?

Discussion

Loading…