O'Reilly logo

CSS: The Missing Manual, 2nd Edition by David Sawyer McFarland

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4. Saving Time with Style Inheritance

Children inherit traits from their parents—eye color, height, male-pattern baldness, and so on. Sometimes, we inherit traits from more distant ancestors, like grandparents or great-grandparents. As you saw in the previous chapter, the metaphor of family relations is part of the structure of HTML as well. And just like humans, HTML tags can inherit CSS properties from their ancestors.

What Is Inheritance?

In a nutshell, inheritance is the process by which some CSS properties applied to one tag are passed on to nested tags. For example, a <p> tag is always nested inside of the <body> tag, so properties applied to the <body> tag get inherited by the <p> tag. Say you created a CSS tag style (Tag Selectors: Page-Wide Styling) for the <body> tag that sets the color property to a dark red. Tags that are descendents of the <body> tag—that is, the ones inside the <body> tag—will inherit that color property. That means that any text in those tags—<h1>, <h2>, <p>, whatever—will appear in that same dark red color.

Inheritance works through multiple generations as well. If a tag like the <em> or <strong> tag appears inside of a <p> tag, then the <em> and the <strong> tags also inherit properties from any style applied to the <body> tag.

Note

As discussed in Chapter 3, any tag inside of another tag is a descendent of that tag. So a <p> tag inside the <body> tag is a descendent of the <body>, while the <body> tag is an ancestor of the <p> tag. Descendents (think kids and grandchildren) inherit properties from ancestors (think parents and grandparents).

Although this sounds a bit confusing, inheritance is a really big time saver. Imagine if no properties were passed onto nested tags and you had a paragraph that contained other tags like the <em> tag to emphasize text or the <a> tag to add a link. If you created a style that made the paragraph purple, 24px tall, using the Arial font, it would be weird if all the text inside the <em> tag reverted to its regular, "browser boring" style (see Figure 4-1). You'd then have to create another style to format the <em> tag to match the appearance of the <p> tag. What a drag.

Inheritance lets tags copy properties from the tags that surround them.Top: The paragraph tag is set with a specific font-family, size, and color. The tags inside each paragraph inherit those properties so they look like the rest of the paragraph.Bottom: If inheritance didn't exist, the same page would look like this figure. Notice how the strong, em, and a tags inside the paragraph retain the font-family, size, and color defined by the browser. To make them look like the rest of the paragraph, you'd have to create additional styles—a big waste of time.

Figure 4-1. Inheritance lets tags copy properties from the tags that surround them. Top: The paragraph tag is set with a specific font-family, size, and color. The tags inside each paragraph inherit those properties so they look like the rest of the paragraph. Bottom: If inheritance didn't exist, the same page would look like this figure. Notice how the strong, em, and a tags inside the paragraph retain the font-family, size, and color defined by the browser. To make them look like the rest of the paragraph, you'd have to create additional styles—a big waste of time.

Inheritance doesn't just apply to tag styles. It works with any type of style; so when you apply a class style (see Class Selectors: Pinpoint Control) to a tag, any tags inside that tag inherit properties from the styled tag. Same holds true for ID styles, descendent selectors, and the other types of styles discussed in Chapter 3.

How Inheritance Streamlines Style Sheets

You can use inheritance to your advantage to streamline your style sheets. Say you want all the text on a page to use the same font. Instead of creating styles for each tag, simply create a tag style for the <body> tag. (Or create a class style and apply it to the <body> tag.) In the style, specify the font you wish to use, and all of the tags on the page inherit the font: body { font-family: Arial, Helvetica, sans-serif; }. Fast and easy.

You can also use inheritance to apply style properties to a section of a page. For example, like many web designers, you may use the <div> tag (The Importance of the Doctype) to define an area of a page like a banner, sidebar, or footer. By applying a style to a <div> tag, you can specify particular CSS properties for all of the tags inside just that section of the page. If you want all the text in a sidebar to be the same color, you'd create a style setting the color property, and then apply it to the <div>. Any <p>, <h1>, or other tags inside the <div> inherit the same font color.

Note

You'll find lots more uses for the <div> tag when laying out a page using CSS in Part III.

The Limits of Inheritance

Inheritance isn't all-powerful. Many CSS properties don't pass down to descendent tags at all. For example, the border property (which lets you draw a box around an element) isn't inherited, and with good reason. If it were, then every tag inside an element with the border property would also have a border around it. For example, if you added a border to the <body> tag, then every bulleted list would also have a box around it, and each bulleted item in the list would also have a border (Figure 4-2).

Note

There's a complete list of CSS properties in Appendix A, CSS Property Reference, including details on which ones get inherited.

Here are examples of times when inheritance doesn't strictly apply:

  • As a general rule, properties that affect the placement of elements on the page or the margins, background colors, and borders of elements aren't inherited.

    Fortunately, not all properties are inherited. The border applied to the paragraphs at top isn't inherited by the tags inside those paragraphs. If they were, you'd end up with an unattractive mess of boxes within boxes within boxes (bottom).

    Figure 4-2. Fortunately, not all properties are inherited. The border applied to the paragraphs at top isn't inherited by the tags inside those paragraphs. If they were, you'd end up with an unattractive mess of boxes within boxes within boxes (bottom).

  • Web browsers use their own inherent styles to format various tags: Headings are big and bold, links are blue, and so on. When you define a font-size for the text on a page and apply it to the <body> tag, headings still appear larger than paragraphs, and <h1> tags are still larger than <h2> tags. It's the same when you apply a font color to the <body>; the links on the page still appear in good old-fashioned, web-browser blue.

    Note

    It's usually a good idea to eliminate these built-in browser styles—it'll make designing sites that work consistently among different browsers easier. In the next chapter, on Starting with a Clean Slate, you'll learn how to do that.

  • When styles conflict, the more specific style wins out. In other words, when you've specifically applied CSS properties to an element—like specifying the font size for an unordered list—and those properties conflict with any inherited properties—like a font-size set for the <body> tag—the browser uses the font size applied to the <ul> tag.

Note

These types of conflicts between styles are very common, and the rules for how a browser deals with them are called the cascade. You'll learn about that in the next chapter.

Tutorial: Inheritance

In this three-part tutorial, you'll see how inheritance works. First, you'll create a simple tag selector and watch it pass its characteristics on to nested tags. Then, you'll create a class style that uses inheritance to alter the formatting of an entire page. Finally, you'll see where CSS makes some welcome exceptions to the inheritance rule.

To get started, you need to download the tutorial files located on this book's companion website at www.sawmac.com/css2e. Click the tutorial link and download the files. All of the files are enclosed in a Zip archive, so you'll need to unzip them first. (Detailed instructions for unzipping the files are on the website.) The files for this tutorial are contained in the folder named 04.

A Basic Example: One Level of Inheritance

To see how inheritance works, start by adding a single tag style and see how it affects the tags nested inside. The next two parts of this tutorial will build upon your work here, so save the file when you're done.

  1. Open the file inheritance.html in your favorite text editor.

    Now add an internal style sheet to this file.

    Note

    In general, it's better to use external style sheets for a website, for reasons discussed in Chapter 2 (Understanding Style Sheets). But sometimes it's easier to start your CSS-based design in an internal style sheet, as in this example, and turn it into an external style sheet later.

  2. Click directly after the closing </title> tag. Hit Enter (Return), and then type <style type="text/css">. Press Enter twice, and type the closing tag—</style>—to indicate the end of the style sheet.

    These tags mark the area where CSS instructions go.

    Now, you'll create a style that applies to all <p> tags.

  3. Click in the empty line between the opening and closing <style> tags and type p {. Hit Enter twice and type the closing brace: }.

    You've created a tag selector that applies to all <p> tags on the page.

  4. Click between the two braces and type color: #FF6600;. The completed style should look like this:

    p {
      color: #FF6600;
    }

    As you've seen in the previous tutorials, the color property sets the color of text. Your style sheet is complete.

  5. Open the page in a web browser to preview your work.

    The color of the page's four paragraphs has changed from black to orange (see Figure 4-3).

But notice how this <p> tag style affects other tags: Tags inside of the <p> tag also change color. For example, the text inside the <em> and <strong> tags inside each paragraph also changes to orange while maintaining its italic and bold formatting. This kind of behavior makes a lot of sense. After all, when you set the color of text in a paragraph, you expect all the text in the paragraph—regardless of any other tags inside that paragraph—to be the same color.

Without inheritance, creating style sheets would be very labor intensive. If the <em>, <a>, and <strong> tags didn't inherit the color property from the <p> tag selector, then you'd have to create additional styles—perhaps descendent selectors like p em and p strong—to correctly format the text.

Using Inheritance to Restyle an Entire Page

Inheritance works with class styles as well—any tag with any kind of style applied to it passes CSS properties to its descendents. With that in mind, you can use inheritance to make quick, sweeping changes to an entire page.

  1. Return to your text editor and the inheritance.html file.

    You'll add a new style below the <p> tag style you created.

  2. Click at the end of the closing brace of the p selector. Press Enter (Return) to create a new line, and then type .pageStyle {. Hit Enter twice, and type the closing brace: }.

    You're about to create a new class style that you'll apply to the body tag.

  3. Click between the two braces, and then add the following list of properties to the style:

    font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
    font-size: 18px;
    color: #BD8100;
    width: 900px;
    margin: 0 auto;
    Inheritance in action! Tags inside of a styled tag—the bold, italicized text—display the same color applied to the <p> tag surrounding them.

    Figure 4-3. Inheritance in action! Tags inside of a styled tag—the bold, italicized text—display the same color applied to the <p> tag surrounding them.

    The whole thing should look like this:

    .pageStyle {
      font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
      font-size: 18px;
      color: #BD8100;
      width: 900px;
      margin: 0 auto;
    }

    This completed class style sets a font, font-size, and color. It also sets a width and centers the style on the page (you saw this trick in the previous tutorial on Creating and Applying an ID Selector for creating a fixed, centered area for a page's content).

  4. Find the opening <body> tag (just a couple lines below the style you just created), and then type class="pageStyle".

    The tag should now look like this: <body class="pageStyle">. It applies the class to the body tag. Thanks to inheritance, all tags inside of the body tag (which are also all the tags visible inside a browser window) inherit this style's properties and therefore use the same font.

  5. Save and preview the web page in a browser.

    As you can see in Figure 4-4, your class style has created a seamless, consistent appearance throughout all text in the body of the page. Both headings and paragraphs inside the <body> tag have taken on the new font styling.

The page as a whole looks great, but now look more closely: The color change affected only the headings and the bulleted list on the page, and even though the style specified an exact font-size, the headline text is a different size than the paragraphs. How did CSS know that you didn't want your headings to be the same 18-pixel size as the body text? And why didn't the nested <p> tags inherit your new color styling from the <body> tag?

A style applied to the body tag passes its properties onto all the tags you see in the web browser, making it easy to apply global formatting effects to a page.

Figure 4-4. A style applied to the body tag passes its properties onto all the tags you see in the web browser, making it easy to apply global formatting effects to a page.

Note

Why use a class—pageStyle—instead of a tag style—body—to redefine the look of the page? Well, in this case, a tag style would work fine. But, applying a class (or ID) to the <body> tag is a great way to customize the look of different pages on your site. For example, if all pages on your site share the same external style sheet (External Style Sheets), a body tag style would apply to the <body> tag of every page on your site. But by creating different classes (or IDs) you can create a different style for the <body> tag for different sections of the site or different types of pages.

You're seeing the "cascading" aspect of Cascading Style Sheets in action. In this example, your <p> tags have two color styles in conflict—the <p> tag style you created on Using Inheritance to Restyle an Entire Page and the class style you created here. When styles collide, the browser has to pick one. As discussed on Specificity: Which Style Wins, the browser uses the more specific styling—the color you assigned explicitly for <p> tag. You'll learn much more about the rules of the cascade in the next chapter.

Inheritance Inaction

Inheritance doesn't always apply, and that isn't necessarily a bad thing. For some properties, inheritance would have a negative effect on a page's appearance. You'll see another example of inheritance inaction in the final section of this tutorial. Margins, padding, and borders (among other properties) don't get inherited by descendent tags—and you wouldn't want them to, as you'll see in this example.

  1. Return to your text editor and the inheritance.html file.

    You'll expand on the p tag style you just created.

  2. Locate the p style, click at the end of the color property (color : #FF6600;), and then press Enter (Return) to create a new line.

    You'll indent the paragraphs on the page by adding a left margin.

  3. Add three properties to the style so that it looks like this:

    p {
      color: #FF6600;
      margin-left: 50px;
      padding-left: 20px;
      border-left: solid 25px #BD8100;
    }

    The margin-left property indents the paragraph 50 pixels from the left; the padding property indents the paragraph text 20 pixels from the border.

  4. Save the file and preview it in a web browser.

    Notice that all of the <p> tags are indented 50px from the left edge of the browser window and that they each have a thick brown border on the left. However, the tags inside the <p> tag (for example, the <em> tag) don't have any additional indentation or border (see Figure 4-5). This behavior makes sense: It would look weird if there were an additional 50px of space to the left of each <em> and each <strong> tag inside of a paragraph!

    To see what would happen if those properties were inherited, edit the p selector so that it looks like this: p, p *, which makes it into a group selector (Constructing Group Selectors). The first part is just the p selector you already created. The second part—p *—means "select all tags inside of a p tag and apply this style to them." (The *, or universal selector, is described on Constructing Group Selectors.)

    While most properties are inherited (like font color), there are plenty—like margins, padding and borders—that don't pass on to nested tags. The CSS Property Reference in indicates which properties are and are not inherited.

    Figure 4-5. While most properties are inherited (like font color), there are plenty—like margins, padding and borders—that don't pass on to nested tags. The CSS Property Reference in Appendix A indicates which properties are and are not inherited.

    Note

    You can find a completed version of the page you created in this tutorial in the 04_finished folder.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required