Inheritance
A key feature to CSS is it's ability to to rely on ancestor-descendant relationship. Inheritance can apply properties of the parent
element to its descendants via the document tree. Descendant elements may inherit text-related properties but not box-related properties. Some inherited
properties include color, font, line-height, text-align, and text-transform. Properties not inherited include background, border, display, height, width,
and padding.
Example of Text-related Inheritance
Consider the following styling:
div {color: red;}
All span elements would have red text. To illustrate this, examine this code:
<div>This <em>illustrates</em> how inheritance works</span>
Which would render this:
This illustrates how inheritance works
The <em> element was not assigned any text color yet it inherited it from it's parent element. If you wish for nested elements to not inherit the
effects of it's parent, you would have to write a class to affect it as such. If the elements were a box within a box element type, the same would be true.
Example of Box-related Inheritance
This example of a test and box-relate property: CSS rules
.bg1 {
background: #999999;
padding: 5px;
}
.red {color: red;}
HTML elements that will receive the CSS rules:
<div class="bg1">
<p class="red">
Paragraph nested inside a div element
</p>
</div>
These two rules applied to the two elements would render this:
Paragraph nested inside a div element
In this example, it may look like the paragraph element has inherited the background from the span element but when we look at the next code example with the
paragraph element also declaring a background color, we'll see that in fact it did not inherited anything. The default property of background of the
paragraph element is set to none which allows for the parent element's property to pass through.
.bg1 {
background: #999999;
padding: 5px;
}
.bg2 {background: #222222;}
And now a slightly modified set of HTML elements:
<div class="bg1">
<p class="bg2 red">
Paragraph nested inside a div element
</p>
</div>
Paragraph nested inside a div element
As you can see, the paragraph element (with the class of .bg2) has it's own background color now while the outer element (class of .bg1) has a background
that is different from it's child element.
As you can see, inheritance is a powerful tool to use when designing your CSS rules.
Having problems with elements displaying in a way that you didn't expect? Chances are that your elements may have inherited something you didn't intend.
You can either review potentially hundreds of lines of CSS code or use a browser to debug your code.