HTML and CSS · Lesson 5 of 12
Selectors, specificity and the cascade
When two CSS rules disagree, which one wins? The answer is the cascade: importance, then specificity, then order. Know it and CSS stops feeling random.
Selectors
p: every p element..card: every element with class="card".#main: the element with id="main".nav a: a elements inside a nav (descendant).ul > li: direct children only.a:hover,input:focus,li:first-child,li:nth-child(odd): pseudo-classes, for states and positions.input[type="email"]: attribute selectors.
Which rule wins
When rules conflict on the same property:
- Importance:
!importantbeats everything (use it almost never). - Specificity: inline style > id > class, attribute or pseudo-class > element. Count them as (ids, classes, elements):
#nav .item ais (1, 1, 1) and beats.nav .item a(0, 2, 1). - Order: with equal specificity, the rule that comes later wins.
Some properties (colour, font) are also inherited by children; others (border, padding) aren't.
Your turn
Make the second paragraph red without changing the HTML and without !important, even though a rule already makes .note paragraphs grey.
Show a solution
<style>
.note { color: grey; }
.note.urgent { color: red; }
</style>
<p class="note">First note</p>
<p class="note urgent">Second note</p>In the interview
How does CSS decide which rule applies?
First !important, then specificity (inline > id > class/attribute/pseudo-class > element), then source order: the later rule wins among equals. Inherited values lose to any rule aimed at the element itself.
Why avoid ids and !important for styling?
They are hard to override, so the next change needs an even stronger selector, and specificity escalates. Classes keep specificity low and even, which makes CSS predictable.
What is the difference between "div p" and "div > p"?
div p matches any p inside a div at any depth; div > p only matches p elements that are direct children of the div.