CSS Inheritance Guide
CSS inheritance is a feature that allows certain CSS properties applied to a parent element to be passed down to its child elements.
What is CSS inheritance?
CSS inheritance allows certain styles applied to a parent element to be passed down to its children. This helps you maintain consistent typography and text colors across your website without repeating the same CSS rules.
For example, when you set a font-family or color on the <body> element, many of its child elements will automatically use those same styles unless another rule overrides them.
This makes it easier to maintain consistent styling throughout a webpage without having to write the same CSS rule for every element.
CSS inheritance example
<div class="parent">
<h2>Welcome</h2>
<p>This paragraph inherits the text color.</p>
</div>
CSS
.parent {
color: #2563eb;
font-family: Arial, sans-serif;
}
Welcome
This paragraph inherits the text color.
Example result: both elements use the parent's blue text color.
Common mistakes
- Not every CSS property is inherited. Properties such as
color,font-family, andfont-sizecommonly inherit from a parent, while properties such asmargin,padding,border, andwidthgenerally do not. - When a child element has its own CSS rule, that rule can override the inherited value.
- CSS also provides the
inheritvalue, which can be used to explicitly tell an element to take the value of a particular property from its parent.
Understanding inheritance
Understanding inheritance is important because it helps you write cleaner, more efficient CSS.
Instead of styling every element individually, you can establish common styles on a parent element and allow its children to inherit them.
This reduces repetition and makes your stylesheet easier to manage and update.
Knowing which properties inherit and how parent and child rules interact will also help you understand why certain styles appear on a webpage and how to control them effectively.
Practice exercise
Change the parent's text color and font, then observe what happens to the child elements.
Welcome
This paragraph inherits the text color.