Overview
Pseudo-classes select elements by state or position and score (0,1,0); pseudo-elements select parts of an element and score (0,0,1). Basic, combinator, and logical selectors are in css-selectors.
State pseudo-classes
Use :focus-visible for focus rings: it shows for keyboard focus and hides on mouse clicks.
| Pseudo-class | Matches |
|---|---|
:hover, :active | Pointer over / being pressed. |
:focus, :focus-visible, :focus-within | Focused / focus the browser shows / contains a focused element. |
:checked, :disabled, :required | Form control state. |
:valid, :invalid | Validity, evaluated from page load. |
:user-invalid | Invalid after the user interacted, so empty required fields do not flash red. |
:empty | No children, whitespace text included. |
:target | Element matching the URL fragment. |
:root | The document root (html). |
:link, :visited | Unvisited / visited links (:visited styling is restricted for privacy). |
Structural pseudo-classes
Use :nth-of-type when siblings have different tags and :nth-child when position alone matters.
| Pseudo-class | Matches |
|---|---|
:first-child, :last-child, :only-child | Position among all siblings. |
:first-of-type, :last-of-type | Position among siblings of the same tag. |
:nth-child(2), :nth-child(odd), :nth-child(3n) | Second / odd / every third child (1-based). |
:nth-last-child(1) | Counted from the end. |
:nth-of-type(2) | Second of its tag. |
:nth-child counts siblings of any tag; p:nth-child(2) matches only a p that is also the second child.
Pseudo-elements
Use the double-colon form; single-colon :before and :after are legacy spellings.
| Pseudo-element | Targets |
|---|---|
::before, ::after | Generated content inside the element. |
::first-line, ::first-letter | First rendered line / letter. |
::marker | List bullet or number. |
::placeholder | Input placeholder text. |
::selection | Selected text. |
::backdrop | Backdrop of a modal <dialog> or fullscreen element. |