Style Inheritance

To simplify the definition of styles in CSS, the mechanism of style inheritance is used. This mechanism assumes that nested elements can inherit the styles of their container elements. For example, let’s say we have a heading and a paragraph on a web page that should have red text. We can separately apply the appropriate style to the paragraph and heading, which will set the desired font color:

However, because both the p element and the h2 element are in the body element, they inherit many styles from that container, the body element. And in order not to duplicate the style definition, we could write this:

As a result, the definition of styles became easier, but the result remained the same.

If we do not want the inherited style, then we can override it for certain elements:

body {
        color: red;
    }
    p {
        color: green;
    }

With multiple levels of nesting, elements only inherit the styles of the closest container:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Style Inheritance in CSS3</title>
    <style>
        body {
            color: red;
        }

        div {
            color: black;
        }
    </style>
</head>

<body>
    <div>
        <h2>Style Inheritance</h2>
        <p>Text about style inheritance in CSS 3 </p>
    </div>
    <p>Copyright &copy; example.com</p>
</body>

</html>

html structure and style inheritance in css

For the div element, the text color is overridden. And since the h2 element and one of the paragraphs are in a div element, they inherit the style of the div element. The second paragraph is directly in the body element and therefore inherits the style of the body element.

style inheritance in css

However, not all CSS properties apply style inheritance. For example, properties that represent margins (margin, padding) and borders (border) of elements are not inherited.

In addition, default browsers also apply a number of preset styles to elements. For example, headings have a certain height, etc.