Unit 3 · CSS: the look and the layout
Does the last CSS rule always win?
No. The more specific selector wins wherever it sits in the file. Order only breaks a tie between rules that are equally specific: then the later one wins.
The mix-up
What people often think
“The rule written last always wins.”
What the tutor says
Order only decides between rules that are equally specific. A more specific selector wins wherever it sits in the file.
In round two, which selector is more specific: .note or body p?
How it works
Specificity is a ranking. Ids beat classes, classes beat element names, and classes add up, so .btn.primary (two classes) beats .primary (one).
Order matters when specificity ties. .btn and .btn-danger are one class each, so whichever comes later wins. Put the variant after the base rule, or the base colour paints over it.
Side by side
.btn-danger { background: red; }
.btn { background: navy; } /* wins: same specificity, later */.btn { background: navy; }
.btn-danger { background: red; } /* wins the tie */Close cousins of this mix-up
The tutor watches for these in the same lesson.
“The last rule in the file wins.”
button is the least specific selector here. Order only matters when two rules tie on specificity.
“The order of the rules does not matter.”
.btn and .btn-danger are equally specific, so the later one wins. Put .btn-danger after .btn, or the navy paints over the red.
Practise it with a tutor watching
The cascade and specificity
Predict which CSS rule wins when several target the same element, and fix fights without !important.
Free, no account needed.