Inheritance

Viewing a document as a tree is very important for one other reason: a key feature of CSS is inheritance , which relies on the ancestor-descendant relationship to operate. Inheritance is simply the mechanism by which styles are applied not only to a specified element, but also to its descendants. If a color is applied to an H1 element, for example, then that color is applied to all text in the H1, even the text enclosed within child elements of that H1:

H1 {color: gray;}

<H1>Meerkat <EM>Central</EM></H1>

As shown in Figure 2-23, both the ordinary H1 text and the EM text are colored gray because the value of color inherits into the EM element. This is very likely what the author intended, which is why inheritance is a part of CSS.

Inheritance of styles

Figure 2-23. Inheritance of styles

The alternative would be a hypothetical situation where inheritance does not operate; in that case, the EM text would be black, not gray.

Another good example of how inheritance works is with unordered lists. Let’s say we apply a style of color: gray for UL elements. What we expect is that a style that is applied to a UL will be applied to its list items as well, and to any content of those list items. Thanks to inheritance, that’s exactly what does happen, as Figure 2-24 demonstrates:

UL {color: gray;}
Inheritance of styles

Figure 2-24. Inheritance ...

Get Cascading Style Sheets: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.