Understanding Cascade, Inheritance, and Specificity
At some point, you will be working on a project and you will find that the CSS you thought should be applied to an element is not working. Usually, the problem is that you have created two or more conflicting CSS rules which point to the same element. Cascade, Inheritance, and Specificity control how CSS is applied when there are conflicting rules.
What is Specificity?
Specificity is how browsers decide which rule to apply if multiple rules have different selectors but could still apply to the same element.
It is basically a measure of how specific a selector’s selection will be:
- An element selector is less specific — it will select all elements of that type that appear on a page — so will get a lower score.
- A class selector is more specific — it will select only the elements on a page with a specific class attribute value, so it will get a higher score.
e.g We can color the text of an element in the body using either body selector or more specifically element selector. If we used both, the more specific one will be applied by the browser.
What is Cascade?
At a very simple level, this means that the order of CSS rules matters. When two rules that have equal specificity apply to the same element the one that comes last in the CSS is the one that will be applied.
What is Inheritance?
As the word suggests, some CSS properties set on parent elements are inherited by their child elements this is called Inheritance.
How to deal with it?
There are three factors to consider, listed here in increasing order of importance. Later ones overrule earlier ones:
Let's talk about “!important”
!important is a piece of CSS that you can use to overrule all of the above calculations.