Inheritance
As
important as specificity may be to understanding how declarations are
applied to a document, another key concept is that of inheritance.
Inheritance is 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>
Both the ordinary h1
text and the
em
text are colored gray because the
em
element inherits the value of
color
. If property values could not be inherited
by descendant elements, the em
text would be
black, not gray, and you’d have to color that
element separately.
Inheritance also works well with unordered lists.
Let’s say you apply a style of
color
: gray;
for
ul
elements:
ul {color: gray;}
You expect that a style that is applied to a ul
will also be applied to its list items, and to any content of those
list items. Thanks to inheritance, that’s exactly
what happens, as Figure 3-3 demonstrates.
Figure 3-3. Inheritance of styles
It’s easier to see how inheritance works by turning to a tree diagram of a document. Figure 3-4 shows the tree diagram for a very simple document containing two lists: one unordered and the other ordered.
Figure 3-4. A simple tree diagram
When the declaration color
:
gray;
is applied to the
Get Cascading Style Sheets: The Definitive Guide, Second Edition 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.