CSS Selectors Cheat Sheet

Common CSS selectors and what they match.

Basic selectors

SelectorMatches
*Every element
pAll <p> elements
.cardElements with class card
#mainThe element with id main
.btn.primaryElements with both classes
h1, h2Either selector (a list)

Combinators

SelectorMatches
nav aa anywhere inside nav (descendant)
ul > liDirect children only
h2 + pThe p immediately after an h2
h2 ~ pEvery later sibling p

Attribute selectors

SelectorMatches 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

Pseudo-classes

SelectorMatches
:hover, :focus, :focus-visible, :activeInteraction states
:first-child, :last-child, :only-childPosition 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-shownForm states
:empty, :root, :targetNo children / the html element / the URL #fragment target

Pseudo-elements

::before and ::after (generated content, need content: ""), ::first-line, ::first-letter, ::placeholder, ::selection, ::marker (list bullets).

Specificity

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.

FAQ

Is there a CSS parent selector?

Yes: :has(), supported in all current major browsers. li:has(> a.active) selects list items whose direct child link is active.

Can I use these selectors in JavaScript?

Yes. document.querySelectorAll('ul > li:nth-child(odd)') accepts the same syntax, which is also what Playwright, Puppeteer and Selenium CSS locators use.