Style inheritance in CSS (Cascading Style Sheets) is a mechanism that allows passing style property values from parent elements to child elements in the DOM (Document Object Model) tree. Thanks to inheritance, we can create a consistent appearance for a web page by applying property values defined at higher levels of the element hierarchy.
Inheritance is particularly useful for properties that are inherited by default. This means that the values of these properties applied to a parent element will be automatically inherited by child elements, unless they are overridden in style rules for those elements. Examples of inherited properties include: color (text color), font-family (font family), font-size (font size), and line-height (line height).
However, not all properties are inherited. Some properties, such as background-color (background color), border (border), and padding (inner spacing), are not automatically inherited. For these properties, we must explicitly specify values for child elements.
Style inheritance gives us the ability to create a consistent and harmonious appearance for a web page. We can define general styles at the parent element level and be sure they will be inherited by child elements, which makes it easier to maintain a uniform look across the entire page. At the same time, thanks to the ability to override inherited values, we can customize the appearance of individual elements to achieve the desired visual effects.
To understand how CSS style inheritance works, consider the following example:
1<body>
2 <h1>Inheritance Example</h1>
3 <p>Paragraph with inherited color and font family, but with its own font size.</p>
4</body>1body {
2 font-family: Arial, sans-serif;
3 color: blue;
4}
5p {
6 font-size: 20px;
7}In the example above, the <body> element has font-family and color styles defined. Because these properties are inherited, child elements like <h1> and <p> also adopt the same values for these properties. These values will apply as long as they are not overridden by other styles defined directly for those elements.
For the <p> element, the font-size value was defined directly, so it does not use the inherited value from the parent element.
If you want to explicitly define inheritance or non-inheritance for a specific property, you can use the inherit keyword. For example:
1p {
2 font-size: inherit;
3}In this case, the font-size value for the <p> element will be inherited from its parent, even if this property is not inherited by default.