What is a selector?
A selector is the part of a CSS rule that chooses which elements the declarations apply to. It can match by element type (p), class (.btn), ID (#header), attribute ([type="email"]), state (:hover), position (:nth-child(2)), relationships (nav a) and even by what an element contains (:has(img)).
How selectors are read
Browsers match selectors right to left. For .menu li a, they find every <a>, then check whether it has an <li> ancestor inside a .menu. That is why the rightmost part (the "key selector") matters most for performance, although for typical sites selector speed is rarely a real bottleneck.
Selector lists and grouping
h1, h2, h3 { ... }applies the same rules to several selectors.:is(header, footer) agroups options; it takes the highest specificity of its arguments.:where(...)groups with zero specificity, which is great for easily overridable base styles.
Good practices
- Style with classes; avoid IDs in CSS (their specificity is hard to override).
- Keep selectors short and flat (
.card-titlerather than.page .main .card h2). - Do not rely on deep DOM structure, which breaks when markup changes.
- Use attribute and ARIA-state selectors to style state:
[aria-expanded="true"].
Interview tip
Mention :has(): it finally gives CSS a way to style a parent based on its children (.card:has(img)).
Code example
1<style>2 body { font-family: system-ui; }3 p { margin: 4px 0; } /* type */4 .note { color: #2b4bff; } /* class */5 #intro { font-weight: 700; } /* id */6 input[type="email"] { border: 2px solid; } /* attribute */7 li:nth-child(odd) { background: #f3f4f6; } /* structural */8 a:hover { color: #e11d48; } /* state */9 nav > a { margin-right: 8px; } /* child combinator */10 .card:has(img) { border: 2px dashed #0b1020; }/* parent selector */11 :where(ul) { padding-left: 18px; } /* zero specificity */12</style>13<p id="intro">Selectors pick elements</p>14<p class="note">Class selector</p>15<nav><a href="#">Home</a><a href="#">About</a></nav>16<input type="email" placeholder="email">17<ul><li>One</li><li>Two</li><li>Three</li></ul>18<div class="card"><img src="https://picsum.photos/80/40" alt="" width="80" height="40"> Has an image</div>19<div class="card">No image</div>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.