Looking for the lessons? Get started!
How "child" elements "inherit" the characteristics of their "parents."
The entire Web Design Principles section can be accessed through the menu below.
Unfortunately, not everyone's browser will support the spiffy JavaScript menu behind that innocent-looking button. If your browser won't display the menu, just click on the button and you'll be taken to a separate page with the entire menu displayed in clear, non-JavaScript HTML.
We inherit nothing truly, but what our actions make us worthy of. — George Chapman
One of the concepts behind the idea of the cascading stylesheet is inheritance. The top-level element of any HTML page is its body
; many designers use this as a selector. When you apply an attribute to the body
selector, the other, lower-level elements inherit the attribute. Like this:
body { color: blue; }
With this color: blue;
attribute and value assigned to everything within the body
selector, all the text in your site will appear in blue. This is because of CSS inheritance.
However, if you add the same attribute, and a different value, to a child element such as an h1
, that particular element will appear differently.
Like this:
h1 { color: red; }
In this case, every text element within the body
element except the h1
element will appear in blue. The h1
element will appear in red. This is a further example of inheritance.
Inline elements such as the HTML tag em
can also be styled. Normally, this line of code would only make the emphasized word appear in italics, while the previous styling (the red color) would remain:
<h1> some <em>emphasized</em> text</h1>
However, you can add styling to the particular HTML element that, because of inheritance, would override the earlier red coloring:
em { color: green; }
Now, the h1
would still appear in blue, except for the em
, which is now styled to appear in green.
Parent-Child Relationships in CSS
The idea of "parent-child" relationships in CSS grows directly from the concept of inheritance.
Just as a child inherits eye color and other traits from a parent, a "child" element will inherit styling from a "parent" element.
Try to get used to reading about "parent" and "child" elements in CSS, as it's a commonly used metaphor.
Child elements are contained by parent elements. Therefore, they inherit their properties.
Let's say you have a parent div
and a child p
within that div
.
Your HTML might look something like this:
<div class="foo"> <p>Stuff.</p> </div>
In your stylesheet, you might decide that everything in that div
needs to be red. So here's your CSS:
.foo { color: #ff0000; }
Adding that style to your stylesheet means that the paragraph contained inside the "foo" div
will be red, without your needing to add the color: #ff0000;
selector to that paragraph.
When you find yourself griping, "I made one single change to my stylesheet and now everything looks different!", a basic grasp of the "parent-child" concept will often rescue you.