CSS Inheritance & Cascade
Understand how CSS properties are inherited and how the cascade determines which styles apply.
What is Inheritance in CSS?
Inheritance in CSS is the mechanism by which some property values
applied to a parent element are passed down to its children. Not all
CSS properties are inherited. For example, color and
font-family are inherited, but margin and
padding are not.
-
Inherited Properties:
color,font-family,font-size,line-height, etc. -
Non-inherited Properties:
margin,padding,border,background, etc.
You can force inheritance using the inherit keyword, or
prevent it with initial or unset.
Interactive Example: Inheritance
/* Parent sets color and font-family */
.parent {
color: #3498db;
font-family: 'Segoe UI', Arial, sans-serif;
}
.child {
font-size: 1.2em;
}
What is the Cascade in CSS?
The cascade is the algorithm that determines which CSS rule applies when multiple rules could apply to the same element. It is based on three main factors:
-
Importance (e.g.,
!importantdeclarations) - Specificity (how specific the selector is)
- Source Order (which rule comes last in the CSS)
The browser evaluates these factors in order to resolve conflicts and apply the correct style.
Interactive Example: Cascade & Specificity
/* Multiple rules for the same element */
.box {
background: #f0f4ff;
color: #222;
}
#special {
color: #e74c3c;
}
.box {
color: #3498db !important;
}
Try to predict which color will apply and why. Hover for explanation. The color will be blue (#3498db) because the '!important' rule has the highest priority, overriding both the ID selector and the other class rule.
Best Practices & Tips
- Use inheritance to reduce repetition and keep your CSS DRY.
- Be mindful of the cascade and specificity to avoid unexpected results.
-
Use
inherit,initial, andunsetfor explicit control. -
Avoid overusing
!importantas it makes debugging harder.
Advanced: initial, inherit, unset, revert
CSS provides four special keywords to control property values and inheritance:
-
initial: Sets the property to its default value as defined by the CSS specification, regardless of inheritance. -
inherit: Forces the property to inherit its value from its parent, even if it is not normally inherited. -
unset: Resets the property toinheritif it is naturally inherited, orinitialif not. -
revert: Rolls the property back to the value established by the user-agent or user styles, ignoring author styles.
/* Example: Using initial, inherit, unset, revert */
.parent-demo {
color: #e67e22;
font-weight: bold;
}
.child-inherit {
color: inherit;
}
.child-initial {
color: initial;
}
.child-unset {
color: unset;
}
.child-revert {
color: revert;
}
Try it: Hover over each child to see a tooltip explaining the result!