Overview

Pseudo-classes select elements by state or position; pseudo-elements select parts of an element that are not separate nodes. Every pseudo-class here scores (0,0,1,0), the same as a class; every pseudo-element scores (0,0,0,1), the same as a type selector. For basic, attribute, combinator, and logical selectors (:is, :where, :not, :has), see css-selectors.

Pseudo-classes (state)

State-based selectors react to user input, structure, or form data.

Pseudo-classMatchesSpecificity
:hoverMouse is over the element.(0,0,1,0)
:focusElement has keyboard focus.(0,0,1,0)
:focus-visibleFocus from keyboard, not click.(0,0,1,0)
:activeElement is being activated.(0,0,1,0)
:checkedCheckbox or radio is checked.(0,0,1,0)
:disabledForm control is disabled.(0,0,1,0)
:requiredForm control has required.(0,0,1,0)
:valid / :invalidForm value passes / fails validation.(0,0,1,0)
:emptyElement has no children, including text.(0,0,1,0)
:targetElement matches the URL fragment.(0,0,1,0)
:rootThe document root (usually <html>).(0,0,1,0)
:link / :visitedAnchor link state.(0,0,1,0)

Use :focus-visible for focus rings; it skips the ring on mouse clicks while keeping it for keyboard users.

Pseudo-classes (structural)

Position within a parent. The n is a 1-based index.

Pseudo-classMatches
:first-childFirst child of its parent.
:last-childLast child of its parent.
:only-childSole child of its parent.
:first-of-typeFirst element of its type among siblings.
:last-of-typeLast element of its type among siblings.
:nth-child(2)Second child of its parent.
:nth-child(odd)1st, 3rd, 5th, …
:nth-child(2n+1)Same as odd.
:nth-child(3n)Every third child.
:nth-last-child(1)Counted from the end; same as :last-child.
:nth-of-type(2)Second of its type.

:nth-child counts siblings of any type; :nth-of-type counts siblings of the same type. They are not interchangeable: p:nth-child(2) matches a p only if it is also the second child overall.

Pseudo-elements

Pseudo-elements address parts of an element that are not separate elements.

Pseudo-elementTargetsSpecificity
::beforeGenerated content before the element.(0,0,0,1)
::afterGenerated content after the element.(0,0,0,1)
::first-lineFirst rendered line of a block.(0,0,0,1)
::first-letterFirst letter of the first line.(0,0,0,1)
::markerList bullet or number.(0,0,0,1)
::placeholderForm control placeholder.(0,0,0,1)
::selectionCurrently selected text.(0,0,0,1)
::backdropBackdrop of a <dialog> or fullscreen element.(0,0,0,1)

Pseudo-elements use double colons (::); the single-colon form (:before) is the CSS2 spelling and still works for the originals.