Inheritance in CSS (Live Playground)
Inheritance in CSS is the process by which some styles are passed down from parent elements to their child elements. In this tutorial, you will learn about inheritance in CSS, how certain properties are inherited, and how to control inheritance with the inherit, initial, and unset keywords, along with sample code and simple explanations.
Understanding inheritance
In CSS, some properties are inherited by default, while others are not. Inherited properties typically include font properties, text properties, and list properties. Non-inherited properties generally include box model properties, positioning properties, and background properties.
Example:
/* Inherited properties */
body {
font-family: Arial, sans-serif;
font-size: 16px;
color: darkblue;
}
/* Non-inherited properties */
body {
background-color: lightblue;
margin: 0;
padding: 1em;
}
<body>
<p>This paragraph inherits font-family, font-size, and color from the body element.</p>
</body>
In this example, the paragraph inherits the font-family, font-size, and color properties from the body element.
Controlling inheritance with keywords
The inherit
, initial
, and unset
keywords can be used to control inheritance for specific properties.
inherit
: Applies the computed value of the property from the parent elementinitial
: Applies the initial value of the property, as defined by the CSS specificationunset
: Acts asinherit
if the property is inherited by default, or asinitial
if it is not
Example:
body {
font-size: 16px;
color: darkblue;
}
p {
font-size: inherit;
color: initial;
}
ul {
color: unset;
}
<body>
<p>This paragraph inherits font-size but has the initial value for color.</p>
<ul>
<li>This list item has the unset value for color, so it inherits the color from the body element.</li>
</ul>
</body>
In this example, the paragraph inherits the font-size property from the body element but uses the initial value for the color property. The list item uses the unset value for the color property, which causes it to inherit the color from the body element.
Conclusion
In this tutorial, you learned about inheritance in CSS and how some styles are passed down to child elements. By understanding inheritance and using the inherit, initial, and unset keywords, you can control how styles are applied to elements and create more consistent designs across your web pages.