Inheritance is about how properties trickle down from an element to its children. Certain properties, like font-family
inherit. If you set a font-family on the body
, that font family will be inherited by all the elements within the body
. The same is true for color
, but it is not true for background
or height
which will always default to transparent
and auto
. In most cases this just makes sense. Why would the background inherit? That would be a pain. What if fonts didn't inherit? What would that even look like?
The cascade is about what take precedence when there is a conflict. The rules of the cascade include:
- Later properties override earlier properties
- More specific selectors override less specific selectors
- Specified properties override inherited properties
And so on. The cascade solves any conflict situations. It is the order in which properties are applied.
(update) Specificity is the calculation used to determine selector priority in the cascade. When two selectors apply to the same element, the one with higher specificity takes precedence.
- Inline styles have a very high specificity (
1000
)
- ID's have a specificity of
100
- classes/attributes and pseudo-classes add
10
- elements and pseudo-elements add
1
Add up all the parts in a selector chain to determine the total specificity. In case of a tie, the last selector takes precedence.
Of course, that comes with various edge-cases and caveats. One class will always override plain elements, no matter how many. More targeted selectors are given priority over inherited properties from parent selectors. And you can throw out all your calculations if someone used !important
—?that trumps everything.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…