CSS Selectors Cheat Sheet
From '.class' to '[attr^="val"]' — the selectors that cover almost everything you'll ever need to target in a stylesheet.
A selector picks which elements a rule applies to. Basic selectors (element, .class, #id) target by name; combinators (space, >, +, ~) describe relationships between elements, like 'a link directly inside a nav'.
Pseudo-classes match a state (:hover, :first-child) rather than a fixed attribute, pseudo-elements target a part of an element that isn't its own node (::before, ::placeholder), and attribute selectors match by the presence or content of an HTML attribute.
Basic selectors
| Selector | Meaning | Example |
|---|---|---|
* | Universal selector — matches everything | * { margin: 0; } |
.class | Elements with this class | .card { } |
#id | The element with this ID | #header { } |
element | Type selector | p { } |
Combinators
| Selector | Meaning | Example |
|---|---|---|
A B | B anywhere inside A (descendant) | .nav a { } |
A > B | B is a direct child of A | ul > li { } |
A + B | B immediately follows A (adjacent sibling) | h2 + p { } |
A ~ B | B follows A anywhere (general sibling) | h2 ~ p { } |
Pseudo-classes
| Selector | Meaning | Example |
|---|---|---|
:hover | While the pointer is over the element | a:hover { } |
:first-child | Element that is the first child of its parent | li:first-child { } |
:nth-child(n) | nth child, by formula | li:nth-child(2n) { } |
:not(sel) | Elements that don't match sel | li:not(.active) { } |
:focus | The currently focused element | input:focus { } |
Pseudo-elements
| Selector | Meaning | Example |
|---|---|---|
::before | Generated content before the element | .icon::before { } |
::after | Generated content after the element | .tooltip::after { } |
::placeholder | An input's placeholder text | input::placeholder { } |
::selection | The portion of text the user has selected | ::selection { } |
Attribute selectors
| Selector | Meaning | Example |
|---|---|---|
[attr] | Has the attribute at all | [disabled] { } |
[attr="val"] | Attribute equals exactly val | [type="text"] { } |
[attr^="val"] | Attribute starts with val | [href^="https"] { } |
[attr$="val"] | Attribute ends with val | [src$=".png"] { } |
[attr*="val"] | Attribute contains val | [class*="btn"] { } |