Cascade and Inheritance

Some Basic Definitions

  • CSS Rules

  • Selectors

  • Source Order (which rules come before others)

  • HTML Elements

  • Multiple Rules Applying to the same Element

  • Multiple Conflicting Rules applying to the same element

Conflicting Rules and How they are resolved

  • Cascading

  • Specificity

  • Inheritance

Cascading

Stylesheets cascade — at a very simple level, this means that the order of CSS rules matters; when two rules apply that have equal specificity, the one that comes last in the CSS is the one that will be used

Specificity

How specific rule selectors are

  • An element selector is less specific (tag selector)

  • A class selector is more specific

  • an ID selector is even more specific

Note

A more specific rule will apply even if it appears before a less specific rule

Inheritance

Child Elements Inherit some rules, and would not inherit other rules

CSS Inheritance

Some properties are inherited by child elements, including

  • Color

  • font-family

  • font-weight

Other properties are not inherited by child elements, such as:

  • width

  • height

  • padding

  • border

  • margin

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#controlling_inheritance

CSS provides four special universal property values for overriding inheritance behavior. Every CSS property accepts these values.

  • inherit

  • initial

  • unset

  • revert

and the all CSS property can be used with one of the above value to inherit or unset or initial to the target element(s)

CSS Cascade

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#understanding_the_cascade

There are three factors to consider, listed here in increasing order of importance. Later ones overrule earlier ones:

  • Source Order

  • Specificity

  • !Important

Source Order

If there are more than one rule that have equal weight and that can apply to an element, later declared rules will override (or overwrite) previous ones

Specificity

Property values (within rules) that are more specific will overrule ones that are less specific, even if the less specific ones come has a later source order.

Specificity Scores:

For each Overall Selector of a given rule

  • 1000 for inline styles (html style attribute)

  • 100 for each ID selector contained in the overall rule selector that target an element

  • 10 for each class selector, attribute selector, or pseudo-class contained in the overall selector of a rule

  • 1 for each element selector or pseudo-element contained in the overall selector