Inheritence and specificity
Two rules decide what an element actually looks like. Once these click, CSS stops feeling random.
Inheritance
Some properties flow down from a parent to everything inside it. Set font-family on <body> and the whole page picks it up ~ you don’t style each paragraph separately.
Text-ish properties inherit: color, font-family, font-size, line-height, text-align.
Box-ish properties don’t: border, padding, margin, background, width. A border on a <div> stays on that <div>.
Specificity
When two rules both apply and disagree, the more specific one wins:
- 1Inline
style=""~ beats basically everything. - 2
#id~ very specific. - 3
.class~ moderately specific. - 4
p~ least specific.
Specificity is checked before source order. That’s why a #id rule at the top of your file beats a .class rule at the bottom.
When it ties
If two rules are equally specific, the one written last wins. This is the cascade.
The escape hatch, and why to avoid it
!important overrides all of it. It is also the reason somebody’s stylesheet becomes impossible to work with six months later ~ once you use one, you need another to beat it, and so on. If you find yourself reaching for it, the real fix is usually a more specific selector.
Click to resume
Use the console below.