CSS Selectors Guide & Cheat Sheet
CSS selectors are the foundation of styling web pages.
They allow you to target specific HTML elements and apply styles with precision.
This guide is a quick reference to the most common and modern CSS selectors —
from basic building blocks and combinators to pseudo-classes and advanced features.
Use it to refresh your memory, speed up development, or clear up doubts while writing CSS.
Quick Summary
Some of the most frequently used selectors:
>→ Direct child+→ Immediate sibling~→ General sibling[attr]→ Attribute-based.class/#id→ Class & ID selectors:nth-child(n)→ Target based on position::before / ::after→ Add visual elements
Basic Building Blocks
*→ Universal selector (all elements)element→ Targets an element (p,h1,div)#id→ Selects element with specificid(#header).class→ Selects elements with specificclass(.button)[attr]→ Elements with given attribute ([disabled])[attr=value]→ Attribute with exact value ([type="text"])
Relationships & Combinators
A, B→ Selects bothAandB(h1, h2)A B→ Descendant (div p)A > B→ Direct child (ul > li)A + B→ Adjacent sibling (h1 + p)A ~ B→ General sibling (h1 ~ p)
Interactive States (Pseudo-classes)
:hover→ On hover:focus→ On focus (inputs, buttons):active→ While being clicked:first-child→ First child of parent:last-child→ Last child of parent:nth-child(n)→ Selects nth child (li:nth-child(2)):nth-of-type(n)→ nth child of same type (p:nth-of-type(2)):only-child→ Only child of its parent:not(selector)→ Excludes selector (p:not(.intro)):empty→ Elements with no children (div:empty)
Pseudo-elements
::before→ Insert content before element::after→ Insert content after element::first-letter→ First letter styling::first-line→ First line styling::selection→ Highlighted text styling::marker→ List item bullet/number styling
Attribute Selectors
[attr^=value]→ Starts with ([class^="btn-"])[attr$=value]→ Ends with ([src$=".png"])[attr*=value]→ Contains ([title*="tip"])
Advanced & Modern Selectors
:root→ Root element (html), useful for CSS variables:is(selector, selector)→ Matches any of the listed selectors (:is(h1, h2, h3)):where(selector)→ Like:is()but has zero specificity:has(selector)→ Parent selector (div:has(> img)):checked→ Checked checkboxes/radio inputs:disabled→ Disabled elements (button:disabled):enabled→ Enabled elements (input:enabled):valid/:invalid→ Form validation states:in-range/:out-of-range→ For inputs withmin/max:required/:optional→ Form fields