CSS Selectors Cheat Sheet
Common CSS selectors and what they match.
Common CSS selectors and what they match.
| Selector | Matches |
|---|---|
* | Every element |
p | All <p> elements |
.card | Elements with class card |
#main | The element with id main |
.btn.primary | Elements with both classes |
h1, h2 | Either selector (a list) |
| Selector | Matches |
|---|---|
nav a | a anywhere inside nav (descendant) |
ul > li | Direct children only |
h2 + p | The p immediately after an h2 |
h2 ~ p | Every later sibling p |
| Selector | Matches when the attribute… |
|---|---|
[disabled] | exists |
[type="email"] | equals the value |
[href^="https"] | starts with |
[href$=".pdf"] | ends with |
[class*="col-"] | contains |
[lang|="en"] | is en or starts with en- |
[data-tags~="new"] | contains the word in a space-separated list |
[type="a" i] | matches case-insensitively |
| Selector | Matches |
|---|---|
:hover, :focus, :focus-visible, :active | Interaction states |
:first-child, :last-child, :only-child | Position among siblings |
:nth-child(2n+1), :nth-child(odd) | Every odd child (1st, 3rd…) |
:nth-of-type(3), :nth-last-child(2) | Counting by element type / from the end |
:not(.active) | Elements that do not match |
:is(h1, h2) a, :where(...) | Grouping; :where adds zero specificity |
.card:has(img) | Parent selector: cards that contain an image |
:checked, :disabled, :invalid, :placeholder-shown | Form states |
:empty, :root, :target | No children / the html element / the URL #fragment target |
::before and ::after (generated content, need content: ""), ::first-line, ::first-letter, ::placeholder, ::selection, ::marker (list bullets).
When rules conflict, the more specific selector wins. Count (IDs, classes/attributes/pseudo-classes, elements): #nav .item a is (1, 1, 1) and beats .nav .item a at (0, 2, 1). Inline styles beat all selectors, and !important beats inline styles. If specificity ties, the rule that comes later wins.
Yes: :has(), supported in all current major browsers. li:has(> a.active) selects list items whose direct child link is active.
Yes. document.querySelectorAll('ul > li:nth-child(odd)') accepts the same syntax, which is also what Playwright, Puppeteer and Selenium CSS locators use.