Skip to main content

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:

CSS
/* Inherited properties */
body {
font-family: Arial, sans-serif;
font-size: 16px;
color: darkblue;
}

/* Non-inherited properties */
body {
background-color: lightblue;
margin: 0;
padding: 1em;
}
HTML
<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.

Live Playground, Try it Yourself

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 element
  • initial: Applies the initial value of the property, as defined by the CSS specification
  • unset: Acts as inherit if the property is inherited by default, or as initial if it is not

Example:

CSS
body {
font-size: 16px;
color: darkblue;
}

p {
font-size: inherit;
color: initial;
}

ul {
color: unset;
}
HTML
<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.

Live Playground, Try it Yourself

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.