The cascade: when several rules compete
"I set color: red and the text is still blue." That is, by far, the number-one
question from anyone starting out with CSS. And it's almost never a bug: it's the
cascade doing its job. Several rules touching the same property may apply
to the same element, and the cascade (the C in CSS) is the algorithm that
decides which one wins. The browser orders them, in this order of priority:
- Origin and importance. The author's stylesheets (yours) carry more weight than
the browser's defaults. A declaration with
!importantis bumped up a level. - Specificity. With equal origin, the most specific selector wins (we look at this in detail in the next lesson).
- Order of appearance. If specificity ties, the last declared rule wins.
p { color: black; }
p { color: blue; } /* this one wins: same specificity, comes later */
In the example both rules have identical specificity, so order decides:
the <p> is painted blue. Quick mental rule: when weights tie, the one you
wrote last wins. That's why sometimes just moving a rule a few lines down is
enough for it to finally "apply".
Inheritance: properties that travel downwards
Some properties, if not specified, are inherited from the parent element. They are mainly those related to text:
- Inherited:
color,font-family,font-size,line-height,text-align,visibility... - Not inherited:
margin,padding,border,background,width,height,display...
body { color: #333; font-family: system-ui; }
/* A <p> inside <body> inherits color and font-family
even if it has no rule of its own. */
You can force the behavior with special values:
.box { color: inherit; } /* inherits explicitly from the parent */
a { color: inherit; } /* the link takes the color of the surrounding text */
Inheritance avoids repeating rules: you define the base typography in body once and
the whole document respects it except where you override it. Think of it like a
family surname: the child carries it without asking, until they decide to change
it on purpose.