DevNotes
@devnotes ·
CSS Part 2: Which rule wins, and why
You write a rule, refresh, and nothing changes. Usually another rule is winning, and the browser has clear rules about which one.
Two rules, one element
Both rules pick the same paragraphs, so the browser has to choose one colour. It picks green. When two rules are equally specific, the one that comes later wins. That's the "cascading" in Cascading Style Sheets.
Specificity: the more precise selector wins
Order only breaks ties. Before that, the browser checks how specific each selector is:
- An id (
#intro) beats any number of classes. - A class (
.note), an attribute selector or a state like:hoverbeats any number of plain element selectors. - An element selector (
p) is the weakest.
The text is red, even though the #intro rule comes first. Move it anywhere in the file and it stays red. Selectors that combine parts add up: .card p (a class and an element) beats p alone, and .card .title beats .title.
Styles written straight on the element, in a style attribute, beat all of these.
Why classes are the safe choice
Ids are so strong that overriding one later means writing an even stronger selector, and then the next fix needs a stronger one still. Style with classes, keep selectors short, and the order of your rules does most of the work. Plenty of experienced developers never style with ids at all.
!important
!important beats all of that. It's tempting when you're stuck, but it only moves the fight up a level, and the next fix needs another !important. Use it almost never. If you feel you need it, the real fix is usually a selector that's too strong somewhere else.
Inheritance
Some properties pass down from a parent to everything inside it. Mostly text ones: color, font-family, font-size, line-height. Set them once on the body and the whole page follows:
Box properties like border, padding, margin and background don't pass down. Imagine every element inside a box getting its own border too.
One catch: links and form fields come with their own browser styles. A link stays blue and an input keeps the browser's font until you style them directly, for example with a { color: inherit; } and input { font: inherit; }.
Find the winner in DevTools
Inspect the element and look at the Styles panel. Every matching rule is listed, the strongest at the top, and any declaration that lost is crossed out. Hover over a selector to see its specificity. When something "doesn't work", this tells you why in seconds.
Try it
Give a paragraph a class and an id. Write three rules for it, one per kind of selector, each with a different colour. Guess which colour wins, then check in DevTools. Swap the order of the rules and check again.
Next: CSS Part 3: The box model
Join WIK to like and reply to DevNotes and see more like this.