How CSS Finds the Elements to Style
Selectors
Type, class, id, attribute, pseudo-class, combinators — the toolkit for matching elements.
What you'll learn
- Use type, class, id, attribute, and descendant selectors
- Combine selectors
- Use pseudo-classes and pseudo-elements
A selector picks which elements a rule applies to. Master a handful and you’ve got most of CSS.
The Basics
| Selector | Matches |
|---|---|
h1 | All <h1> elements |
.card | All elements with class="card" |
#nav | The element with id="nav" |
* | Everything |
[type="email"] | Inputs with type="email" |
[data-state] | Anything with a data-state attribute |
h1 { color: tomato; }
.card { padding: 1rem; }
#nav { position: sticky; }
[type="email"] { font-style: italic; } Combinators
Combine selectors to navigate the tree.
| Combinator | Meaning |
|---|---|
A B | B is a descendant of A (any depth) |
A > B | B is a DIRECT child of A |
A + B | B is the IMMEDIATELY following sibling |
A ~ B | B is any following sibling |
.card h2 { color: tomato; } /* any h2 inside .card */
.card > h2 { color: tomato; } /* direct child h2 only */
h2 + p { font-size: 1.1rem; } /* the first p after an h2 */ Multiple Selectors (Same Rule)
Comma-separate to apply one rule to many selectors:
h1, h2, h3 {
font-family: "Inter", sans-serif;
} Pseudo-Classes — State Selectors
| Pseudo-class | When it matches |
|---|---|
:hover | Mouse is over the element |
:focus | Element has focus |
:focus-visible | Focused via keyboard (better than :focus) |
:active | Being clicked |
:checked | A checked checkbox/radio |
:disabled / :enabled | Form state |
:first-child | First among its siblings |
:last-child | Last among its siblings |
:nth-child(2n) | Even children (or any formula) |
:not(.x) | Anything NOT matching .x |
:is(.x, .y) | Anything matching .x OR .y |
:has(.x) | Has a .x descendant |
a:hover { text-decoration: underline; }
button:focus-visible { outline: 2px solid blue; }
li:nth-child(odd) { background: rgb(0 0 0 / 5%); }
input:not([type="hidden"]) { display: block; } Pseudo-Elements — Style Bits of an Element
| Pseudo-element | What it is |
|---|---|
::before | Inserted before the element’s content |
::after | Inserted after the element’s content |
::first-line | The first line of text |
::first-letter | The first character |
::placeholder | An input’s placeholder text |
::selection | Selected text |
.required::after { content: " *"; color: red; }
::selection { background: yellow; } (Two colons :: is the modern syntax. Single colon still works for
the originals.)
Attribute Selectors With Patterns
a[href^="https://"] { /* starts with https:// — external link */ }
a[href$=".pdf"] { /* ends with .pdf */ }
a[href*="example"] { /* contains "example" */ } Up Next
When multiple rules match the same element, who wins? The cascade.
The Cascade →