Jitendra Vyas Jitendra Vyas - 1 year ago 66
CSS Question

In CSS, what is the difference between cascading and inheritance?

In CSS, what is the difference between cascading and inheritance?

Or are both the same thing?

Answer Source

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:

  1. Later properties override earlier properties
  2. More specific selectors override less specific selectors
  3. 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.

  1. Inline styles have a very high specificity (1000)
  2. ID's have a specificity of 100
  3. classes/attributes and pseudo-classes add 10
  4. 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download