Chapter 1 covered basic selectors. CSS has a far richer selection language that lets you target elements by relationship, attribute and state — often removing the need to add extra classes or JavaScript. Mastering selectors is what makes stylesheets concise.
Combinators
| Selector | Matches |
|---|---|
a b | b anywhere inside a (descendant) |
a > b | b that is a direct child of a |
a + b | b immediately after a (adjacent sibling) |
a ~ b | any b after a (general sibling) |
nav > li { } /* only top-level items, not nested */h2 + p { } /* the paragraph right after an h2 */label ~ input { } /* inputs that follow a label */
Attribute selectors
input[type="email"] { } /* exact match */a[href^="https"] { } /* starts with */a[href$=".pdf"] { } /* ends with */[class*="btn"] { } /* contains */[data-active] { } /* has the attribute at all */
Pseudo-classes
Pseudo-classes (single colon) match a state or position without needing a class:
a:hover, a:focus { text-decoration: underline; }button:disabled { opacity: 0.5; }input:checked { }input:invalid { border-color: red; }li:first-child { }li:last-child { }tr:nth-child(2n) { background: #f6f6f3; } /* zebra stripes */li:nth-child(3) { } /* the third one */
Pseudo-elements
Pseudo-elements (double colon) style a part of an element, or insert generated content:
.badge::before { content: "★ "; } /* insert content */.card::after { content: ""; display: block; clear: both; }p::first-line { font-weight: 600; }::selection { background: #dbeafe; } /* highlighted text */input::placeholder { color: #94a3b8; }
:is, :where & :not
These modern selectors keep long rules readable:
/* Instead of h1 a, h2 a, h3 a { … } */:is(h1, h2, h3) a { color: inherit; }/* :where is the same but adds ZERO specificity — great for resets */:where(ul, ol) { margin: 0; }/* :not excludes */button:not(.primary) { background: transparent; }
Practice
Style a nav so only direct child links get a border (>), zebra-stripe a table with :nth-child, add a "→" after external links with a[href^="http"]::after, and style all headings' links in one rule with :is().
Key takeaways
- 01Combinators target by relationship: descendant (a b), child (a > b), siblings (a + b, a ~ b).
- 02Attribute selectors match by attribute with ^= $= *= and presence [attr].
- 03Pseudo-classes (:hover, :checked, :nth-child, :first-child) match state and position.
- 04Pseudo-elements (::before/::after, ::placeholder, ::selection) style parts or insert content.
- 05:is()/:where() group selectors (:where adds no specificity); :not() excludes.
