CSS Inheritance
In this page:
Which Properties Inherit by Default
Text-related properties like color, font-family, font-size, and line-height inherit by default -- set them on a parent and every nested element picks them up unless it overrides them. This is why setting a global font on body works without repeating it on every paragraph and span.
Example: Which Properties Inherit by Default
<style>
body {
color: navy;
font-family: sans-serif;
}
</style>
<body>
<p>Inherits navy color and the font-family without repeating them</p>
</body>
Which Properties Don't Inherit
Box-model properties like border, margin, padding, width, and background do NOT inherit -- each element starts fresh with its own default box, otherwise every nested div would accidentally inherit its parent's border and padding. This default exists specifically to keep layout properties predictable per element.
Example: Which Properties Don't Inherit
<style>
.parent {
border: 2px solid black;
padding: 20px;
background: lightyellow;
}
</style>
<div class="parent">
<div>Child has no border or padding of its own</div>
</div>
The inherit Keyword
Any property, even ones that don't inherit by default, can be forced to inherit its parent's computed value using the inherit keyword. This is useful when you want a child to deliberately match its container instead of falling back to the property's normal initial value.
Example: The inherit Keyword
<style>
.parent {
border-color: blue;
background: lightyellow;
padding: 10px;
}
.child {
border: 2px solid black;
border-color: inherit;
padding: 8px;
background: white;
}
</style>
<div class="parent">
<div class="child">Border forced to match the parent's border-color</div>
</div>
The initial Keyword
The initial keyword resets a property to its default value as defined by the CSS specification, ignoring both inheritance and any stylesheet rules. This is handy for undoing an inherited or cascaded value back to the browser's baseline.
Example: The initial Keyword
<style>
p {
color: red;
}
.reset {
color: initial;
}
</style>
<p class="reset">Reset back to the browser's default text color</p>
The unset Keyword
The unset keyword is context-sensitive: on a property that normally inherits, it behaves like inherit; on a property that doesn't inherit, it behaves like initial. It's a convenient single keyword for resetting a property without needing to know its inheritance behavior.
Example: The unset Keyword
<style>
.parent {
color: navy;
}
.child-color {
color: unset;
}
.child-border {
border: 2px solid black;
border-color: unset;
background: lightyellow;
padding: 8px;
}
</style>
<div class="parent">
<p class="child-color">unset acts like inherit here</p>
<div class="child-border">unset acts like initial here</div>
</div>
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: