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.
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.
/* Inherited properties */
font-family: Arial, sans-serif;
/* Non-inherited properties */
<p>This paragraph inherits font-family, font-size, and color from the body element.</p>
In this example, the paragraph inherits the font-family, font-size, and color properties from the body element.
Controlling inheritance with keywords
unset keywords can be used to control inheritance for specific properties.
inherit: Applies the computed value of the property from the parent element
initial: Applies the initial value of the property, as defined by the CSS specification
unset: Acts as
inheritif the property is inherited by default, or as
initialif it is not
<p>This paragraph inherits font-size but has the initial value for color.</p>
<li>This list item has the unset value for color, so it inherits the color from the body element.</li>
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.
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.