CSS
CSS Selectors
CSS selectors determine which HTML elements a rule applies to. Mastering selectors is the key to writing clean, non-repetitive CSS.
/* ── Basic Selectors ────────────────────────── */
div { } /* All <div> elements */
.card { } /* class="card" */
#hero { } /* id="hero" (unique per page) */
* { } /* Every element (universal) */
/* ── Combinator Selectors ───────────────────── */
div p { } /* <p> anywhere inside <div> (descendant) */
div > p { } /* <p> directly inside <div> (child) */
h1 + p { } /* <p> immediately after <h1> (adjacent sibling) */
h1 ~ p { } /* All <p> after <h1> (general sibling) */
/* ── Pseudo-classes (element state) ─────────── */
a:hover { } /* Link on mouse hover */
button:focus { } /* Element when focused */
li:first-child { } /* First <li> in parent */
li:last-child { } /* Last <li> in parent */
li:nth-child(2) { } /* Second <li> */
li:nth-child(odd) { }/* Odd-numbered items */
input:checked { } /* Checked checkbox or radio */
input:disabled { } /* Disabled form element */
p:not(.special) { } /* All <p> except .special */
/* ── Pseudo-elements (part of element) ──────── */
p::first-line { } /* Only the first rendered line */
p::first-letter { } /* Only the first letter */
h2::before { content: "→ "; } /* Insert content before */
h2::after { content: " ←"; } /* Insert content after */
input::placeholder { color: #aaa; }
/* ── Attribute Selectors ─────────────────────── */
input[type="email"] { } /* input with type="email" */
a[href^="https"] { } /* links starting with https */
a[href$=".pdf"] { } /* links ending with .pdf */
img[alt] { } /* images that have an alt attribute */
💡
Specificity order (lowest → highest): element (0,0,1) → class/attribute/pseudo-class (0,1,0) → id (1,0,0) → inline style (1,0,0,0). Use !important only as a last resort — it makes debugging very hard.
Watch & Learn
A recommended video to watch alongside this chapter.
More “CSS Selectors” videos on YouTube