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.
Try itEdit the code: the page updates as you type

Which rule wins

When rules conflict on the same property:

  1. Importance: !important beats everything (use it almost never).
  2. Specificity: inline style > id > class, attribute or pseudo-class > element. Count them as (ids, classes, elements): #nav .item a is (1, 1, 1) and beats .nav .item a (0, 2, 1).
  3. Order: with equal specificity, the rule that comes later wins.

Some properties (colour, font) are also inherited by children; others (border, padding) aren't.

Try itEdit the code: the page updates as you type

Your turn

Make the second paragraph red without changing the HTML and without !important, even though a rule already makes .note paragraphs grey.

ExerciseEdit the code: the page updates as you type
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.

Your progress stays on this device.