What is CSS inheritance?
In CSS, certain properties can be automatically passed from a parent element to its child elements.
This is called inheritance.
Why is it important?
Thanks to inheritance, you don't have to redefine each property for each individual element.
This saves time and ensures a consistent design.
What is inherited?
Not all CSS properties are automatically inherited.
Typical inheritable properties include:
color
font-family
line-height
For example, if you assign a text color to a <div>
, this color will be inherited by the <p>
elements it contains.
Code Example
<div>
<p>Text in a Paragraph</p>
</div>
div {
color: red;
}
The <p>
element automatically inherits the font color of the
What is not inherited?
Non-inherited properties must be set explicitly for each element.
Examples:
margin
padding
border
background
Code Example:
<div>
This is the parent element with padding.
<p>This is the child element</p>
</div>
div{
border: solid 1px red;
}
If you want to explicitly inherit this, you must set it in the child element using inherhit.
<div>
This is the parent element with padding.
<p style="border: inherit;">This is the child element</p>
</div>
Keywords inherit
, initial
, unset
inherit
Resets the property to its default value (as defined by the browser).
unset
(combination of inherit and initial)
Combines both worlds:
For inheritable properties → inherit
For non-inheritable properties → initial
When should you use inheritance specifically?
When multiple child elements share the same properties, inheritance is worthwhile:
body {
font-family: Arial, sans-serif;
color: #333;
}
When is it better not to use it?
Inheritance only works from top to bottom – from parent to child.
If you want to specifically change the design of a single element, you should address it directly or work with classes.
Conclusion
CSS inheritance is a powerful tool for making your stylesheet more efficient and clearer.
If you use it consciously, you save time and avoid repetition in your code.
Thanks
Thank you for reading this far! I'm still new to writing articles and have a lot to learn. I appreciate for your feedback.
Happy coding 😊
Top comments (0)