The Cascade and Inheritance
Review two core concepts of CSS: the cascade and inheritance.
What is the cascade?
The cascade is the “C” in CSS. It’s therefore at the very core of CSS. The cascade algorithm determines the properties applied to page elements.
This determination is based on inheritance, specificity, importance, and rule order. The cascade also ensures that we have no conflicts. If we have multiple CSS rules for the same property and on the same element, the cascade determines which rule is applied.
So, while keeping the cascade in mind, let’s take a look at the rules it uses to make these decisions, starting with inheritance.
Inheritance
CSS inheritance works on the property level. When we set properties to a selector in CSS, they’re either inherited by all children of that selector or not? It depends on the property. Some properties are obviously inheritable, while others aren’t.
When working with fonts, we don’t have to apply our font-family or font-size styles to every element on our page. We can set these styles on the body
tag and every child will inherit it.
Inheritance helps us write our CSS much more concisely by reducing repetition. As a result, we don’t have to explicitly set each property in every child element.
Enforcing a property
If a property isn’t inheritable by default, we can force its children to inherit properties. In the child selector, set the property to inherit
.
For example:
body {
background-color: red;
}
p {
background-color: inherit;
}
Our web page, <body>
is given a red
background-color
. Typically, other elements won’t inherit background properties. We use background-color:
inherit
to enforce this on a <p>
element.
Avoiding property
The reverse is also possible. By using the revert
keyword, the property won’t be inherited from its parent. In this case, the value is reverted to its parent element.
For example:
body {
background-color: red;
}
p {
background-color: revert;
}
Here, with the help of background-color:
revert
, our <p>
element reverts to its default.
Example
Get hands-on with 1400+ tech skills courses.