CSS Inheritance

CSS Inheritance is a feature that allows certain CSS property values to pass from a parent HTML element to its child elements. It helps maintain consistent styles across a webpage without repeating the same CSS rules for every element.

For example, setting a font family on the <body> element can apply that font to many elements inside the page.

How Does CSS Inheritance Work?

When a CSS property is inherited, child elements receive the computed value from their parent unless another applicable rule overrides it.

Consider this example:

<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            color: blue;
            font-family: Arial, sans-serif;
        }
    </style>
</head>
<body>
    <h1>Welcome to Web4Learners</h1>
    <p>Learn HTML and CSS step by step.</p>
</body>
</html>

Both the heading and paragraph inherit the blue text color and Arial font family from the <body> element.

Which CSS Properties Are Inherited?

Some commonly inherited properties include:

  • color
  • font-family
  • font-size
  • font-style
  • line-height
  • text-align
  • visibility

However, many properties, such as margin, padding, border, and background-color, are not inherited by default.

For example:

body {
    color: green;
    background-color: lightgray;
}

Child text can inherit the green color, but child elements do not automatically inherit the body’s background color.

How to Control CSS Inheritance

CSS provides special values that let you control how properties behave.

p {
    color: inherit;
}

h2 {
    color: initial;
}
  • inherit makes an element take the property’s computed value from its parent.
  • initial sets the property to its initial value defined by CSS.
  • unset acts like inherit for normally inherited properties and like initial for other properties.

Why Is CSS Inheritance Important?

CSS Inheritance reduces repeated code and makes styles easier to maintain. Setting common font and text properties on a parent element can help create a consistent design across multiple sections of a webpage.

To understand how inherited styles interact with competing rules, explore our tutorials on CSS Cascade and CSS Specificity.