Chapter 2 of 14
~11 minSelectors & Specificity
Selectors decide which elements a rule applies to, and specificity decides which rule wins when two rules target the same element.
Basic Selector Types
A type selector matches every element of that tag (p). A class selector (.card) matches any element with that class, and an id selector (#header) matches the single element with that id. The universal selector (*) matches everything, and attribute selectors ([type="text"]) match based on an attribute's presence or value.
Try it yourself
<h1 id="main-title">Title</h1> <p class="highlight">Highlighted paragraph</p> <p data-active>Active paragraph</p> <p>Plain paragraph</p>
Combinators
A descendant combinator (a space) matches any element nested anywhere inside another, like .card p. A child combinator (>) matches only direct children, like .card > p. An adjacent sibling combinator (+) matches an element immediately following another, and a general sibling combinator (~) matches any following sibling, not just the immediate one.
Try it yourself
<div class="card"> <h3>Card title</h3> <p>Right after the heading (italic).</p> <div><p>Nested deeper (still green, still matched by descendant rule).</p></div> </div>
How Specificity Is Calculated
When two rules conflict, the browser picks the one with higher specificity. Inline styles beat everything. Next comes id selectors, then classes/attribute selectors/pseudo-classes, then type selectors and pseudo-elements. More specific selectors of the same kind (like two chained classes) beat a single one of that kind.
A rule marked !important overrides normal specificity entirely, which makes it tempting - but it also makes future overrides much harder, since only another !important (or inline style) can beat it. Treat it as a last resort, not a quick fix.
Try it yourself
A class beats a type selector, regardless of source order<p class="green">I am green, because a class is more specific than a type selector.</p>
Coding challenge
Style a .card so only its direct child <h3> is bold, while every <p> inside it (at any depth) is gray.
<div class="card"> <h3>Title</h3> <p>Direct paragraph</p> <div><p>Nested paragraph</p></div> </div>
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/41. Which selector matches only direct children of an element?
2. Which has the highest specificity?
3. What does h2 + p select?
4. Why is !important considered a last resort?