CSS Inheritance
CSS Inheritance
CSS inheritance means some properties are passed from a parent element to its children. This helps keep styles consistent and reduces repeated code.
Not every CSS property is inherited. For example, text-related properties are usually inherited, but layout properties usually are not.
What Is Inherited?
Common inherited properties include:
colorfont-family,font-size,font-weightline-heighttext-align,letter-spacing
Common non-inherited properties include:
margin,padding,borderwidth,heightbackgrounddisplay,position
Inheritance Example
If you set the text color on a parent, child elements inherit it automatically.
.card {
color: #333;
font-family: Arial, Helvetica, sans-serif;
}
<div class="card"> <h3>Title</h3> <p>This text inherits the color and font.</p> <a href="#">This link also inherits (unless overridden).</a> </div>
Using inherit
The inherit keyword forces a property to inherit from the parent even if it normally does not.
A common example is making links inherit the surrounding text color:
.card a {
color: inherit;
text-decoration: underline;
}
initial and unset
CSS also provides keywords to reset or adjust inheritance behavior:
initialresets a property to its default initial valueunsetbehaves likeinheritfor inherited properties, and likeinitialfor non-inherited properties
.title {
color: initial;
}
.note {
color: unset;
}
Why Inheritance Matters
- Cleaner CSS with fewer repeated rules
- Consistent typography across components
- Easier theming by changing styles at a higher level
Code Challenge
Goal: Use inheritance to style a card and make the link match the text color.
HTML:
<div class="card"> <h3>Inheritance</h3> <p>This paragraph inherits styles from the card.</p> <a href="#">This link should match the text color.</a> </div>
Task:
- Set
colorandfont-familyon.card - Make the link use the same color using
inherit - Add a simple underline for the link
Try a Solution:
.card {
max-width: 520px;
padding: 16px;
border: 1px solid #ddd;
border-radius: 12px;
color: #333;
font-family: Arial, Helvetica, sans-serif;
}
.card a {
color: inherit;
text-decoration: underline;
}
What’s Next?
Next, you will learn how CSS specificity decides which rule wins when multiple rules target the same element.