Cascade & Inheritance
The most fundamental concepts of CSS are cascade, specificity, and inheritance.
What happens when you create two CSS rules applied to the same element. To solve this issue cascade and specificity mechanisms are used.
What is cascade in CSS?
When you apply two same rules with the same specificity, one that comes last will apply to the element.
h1 {
color: red;
}
h1 {
color: blue;
}
<h1>This is my heading.</h1>
This is my heading.
What is specificity in CSS?
To understand the specificity please look at the following example.
.heading {
color: red;
}
h1 {
color: blue;
}
<h1>This is my heading.</h1>
This is my heading.
Here, you have two selectors with different rules.
- An element selector is less specific ( h1 selector will have low score)
- A class selector is more specific ( .heading class selector will have higher score)
Specificity is how the browser decides which rule to be applied depending on the score
What is inheritance in CSS?
Some of the CSS properties of the parent element can automatically apply to the child element.
.parent{
color: red;
}
<div class="parent">
Parent Element
<div> Child Element</div>
</div>
Some properties do not inherit: like width
, height
,margin,padding,border
Controlling Inheritance
You can control the inheritance property with four values : inherit
, initial
, unset
, revert
inherit
: inherit the property value from the parent element.
initial
: apply the default (initial) value
unset
: returns to its natural value. If the property can inherit it will apply the inherited value otherwise initial value.
revert
: act like unset in many cases, however, may revert to the browser’s default value