2.3 Pseudo-classes and Pseudo-elements
Ordinary selectors pick "elements that really exist." But sometimes we want to select a certain state of an element (like "while hovered") or a certain position (like "the first child"), or even add content "out of thin air." That's when pseudo-classes and pseudo-elements step in.
The lab below lets you switch between several common pseudo-classes/elements and see the effect live.
Pseudo-classes: an element's "special state" (single colon :)
A pseudo-class starts with one colon and describes what state an element is in right now, or where it sits.
Interaction states:
a:hover { color: red; } /* while hovered */
a:active { color: orange; } /* while being pressed */
input:focus { outline: 2px solid blue; } /* while the input is focused */:hover is one of the most-used pseudo-classes — button and link hover highlights all rely on it.
Position states:
li:first-child { font-weight: bold; } /* the first li in its parent */
li:last-child { border: none; } /* the last li */
li:nth-child(even) { background: #f1f5f9; } /* even items, for zebra stripes */Pseudo-elements: parts conjured "out of thin air" (double colon ::)
A pseudo-element starts with two colons. It can select part of an element, or insert content before or after it.
/* Add a quote mark before each .quote */
.quote::before {
content: "“";
color: gray;
}
/* Select a paragraph's first line / first letter */
p::first-line { font-weight: bold; }
p::first-letter { font-size: 200%; }The most-used are ::before and ::after, used with the content property. They commonly add icons, decorative lines, or quotes — "purely decorative" content that isn't in the HTML, generated entirely by CSS.
:before. In new code, follow the "two colons for pseudo-elements" convention.Quick reference
| Syntax | Type | Meaning |
|---|---|---|
:hover | Pseudo-class | Mouse hovering |
:focus | Pseudo-class | Has focus (e.g., clicked into an input) |
:first-child | Pseudo-class | First child of its parent |
:nth-child(even) | Pseudo-class | Even-positioned children |
::before / ::after | Pseudo-element | Insert generated content before/after |