Приглашаем посетить
Чулков (chulkov.lit-info.ru)

The Cascade

Previous Page
Table of Contents
Next Page

The Cascade

OK, now we have enough information to have a meaningful discussion about one of the toughest aspects of CSS to get your head aroundthe cascade. If this section gets to be too much, skip ahead and read the "Charlie's Simple Cascade Summary" sidebar later in this chapter. This sidebar is a simplified, if slightly less accurate, version that will serve you until you have done some CCS coding and really need the details.

As its name suggests, the cascade in Cascading Style Sheets involves styles falling down from one level of the hierarchy of your document to the next, and its function is to let the browser decide which of the many possible sources of a particular property for a particular tag is the one to use.

The cascade is a powerful mechanism. Understanding it helps you write CSS in the most economical and easily editable way and enables you to create that documents are viewed as you mean them to be seen, while leaving appropriate control of aspects of the document's display, such as overall font sizes, with users who have special needs.

Sources of Styles

Styles can come from many places. First, it's not hard to accept that there must be a browser style sheet (the default style sheet) hidden away inside the browser, because every tag manifests styles without you writing any. For example, h1 tags create large bold type, em tags create italicized type, and lists are indented and have bullets for each item, all automatically. You don't style anything to make this formatting happen.

The Cascade

Learn more about the browser default style sheet on Eric Meyer's blog (www.meyerweb.com/eric/thoughts/2004/09/15/emreallyem-undoing-htmlcss).


If you have Firefox installed on your computer, search for the file html.css and you can then see the Firefox default browser style sheet. Modify it at your peril.

Then there is the user style sheet. The user can create a style sheet, too, although very few do. This capability is handy, for example, for the visually impaired, since they can increase the baseline size of type or force type to be in colors that they can discern one from another. You can add a user style sheet to Internet Explorer for Windows by selecting Tools > Internet options… and clicking the Accessibility button. This capability, for example, enables visually impaired users to add a style like

body {font-size:200%}

that doubles the size of all typeinheritance at work again! This is why it is important to specify type in relative sizes such as ems rather than fixed sizes such as points, so you don't over-ride such changes. We will discuss this interesting topic more in Chapter 3.

Then there are author style sheets, which are written by you, the author. We have already discussed the sources of these: linked style sheets, embedded styles at the top of pages, and inline styles that are attached to tags.

Here's the order in which the browser looks at, or cascades through, the various locations:

  • Default browser style sheet

  • User style sheet

  • Author style sheet

  • Author embedded styles

  • Author inline styles

The Cascade

The cascade defines which style sheet is looked at in which order and which style wins out if a style is defined in two or more places.


The browser updates its settings for each tag's property values (if defined) as it encounters them while looking sequentially in each location. They are defined in the default browser style sheet and the browser updates any that are also defined in the other locations. If, for example, the author style sheet style defines the <p> tag's font-family to be Helvetica but the <p> tag is also specified to be Verdana in an embedded (page) style, the paragraph will be displayed in Verdanathe embedded styles are read after the author style sheet. However, if there is no style for paragraphs in the user or author style sheet, they will display in Times, because that's the style defined in all browser default style sheets.

That's the basic idea of how the Cascade works, but in fact, there are several rules that control the Cascade.

The Cascade Rules

In addition to the order in which styles are applied, you should know several rules about how the cascade works.

The Cascade

Get more info on the cascade at the W3C site (www.w3.org/TR/CSS2/cascade.html).


Cascade Rule 1: Find all declarations that apply to each element and property. As it loads each page, the browser looks at every tag in the page to see if a rule matches it.

Cascade Rule 2: Sort by order and weight. The browser sequentially checks each of the five sources, setting any matched properties as it goes. If a matched property is defined again further down the sequence, the browser updates the value and does this repeatedly, if necessary, until all five possible locations of properties for each tag in that page have been checked. Whatever a particular property is set to at the end of this process, that's how it is displayed.

In Table 2.1, we look at this process for a page with numerous p tags. Let's assume, for the sake of the example, that two of those p tags have inline styles that define their color as red.

Table 2.1. Cascade Example

LOCATION

TAG

PROPERTY

VALUE

Default style sheet

p

Color

black

User style sheet

   

Author style sheet

p

Color

blue

Author embedded styles

   

Author inline styles

p

Color

red


In this case, every p tag text is blue, except for ones with the inline color attributethese are red.

Of course, things aren't quite that simple. There is also the weight of the declaration. You can define a rule as important, like this

p {color:red !important;  font-size:12pt}        <-- a

(a)Note the exclamation point

The word !important follows a space after the style you want to make important but before the ; (semicolon) separator.

This style defines the text's red color as important, and therefore, it displays this way, even if it is declared as a different color further down the cascade. Think hard and long before you force a particular style on the user with !important rule definition, because you may be messing up someone's personal style sheet, which may be set that way for a very good reason; be sure that it truly is important for such a style to dominate over any other possible style for that tag.

Charlie's Simple Cascade Summary

You need to remember just three things in this simplified version of the cascade rules. These are true for virtually every case.

Rule 1: Selectors with IDs win out over selectors with classes; these, in turn, win out over selectors with only tags.

Rule 2: If the same property for the same tag is defined in more than one location in the cascade, inline styles win over embedded styles, which win over style sheet styles. Rule 2 loses out to Rule 1 thoughif the selector is more specific, it wins, wherever it is.

Rule 3: Defined styles win over inherited styles regardless of specificity.

A little explanation is required for Rule 3. This markup


<div id="cascadedemo">
<p id="inheritancefact">Inheritance is <em>weak</em> in the
The Cascade Cascade</p>
</div>

and this rule, which has a high specificity,

html body div#cascadedemo p#inheritancefact {color:blue:}        <-- a

(a)2 - 0 - 4

results in all the text, including the word weak, being blue because the em inherits the color from its parent, the p tag.

As soon as we add this rule for the em, even though it has very low specificity

em {color:red}        <-- a

(a)0 - 0 - 1

the em text is red. The inherited style is overridden by the defined style for the em, regardless of the high specificity of the rule for the containing paragraph.

There, three simple cascade rules. That was much easier, wasn't it?


Cascade Rule 3: Sort by specificity. Besides being very hard to pronounce, specificity determines just how specific a rule is. I tried to get you started on this idea by using the word specific in exactly this way many times while we were discussing selectors. As you saw, if a style sheet contains this rule

p {font-size:12px;}

and this rule

p.largetext {font-size:16px;}

then this markup

<p class="largetext">A bit of text</p>

displays text 16 pixels high because the second rule is more specificit wins.

This may seem intuitively obvious, but what happens to that bit of markup if you use these styles instead?

p {font-size:12px}
.largetext {font-size:16px}

Both these rules match the tag, but the class wins out and the text is 16 pixels. Here's why: the numeric specificity of the tag selector is 1, but the class has a specificity of 1-0. Here's how to calculate the specificity of any selector. There is a simple scoring system for each style that you plug into a three-value layout like this:

A - B - C

The dashes are separators, not subtraction signs. Here's how the scoring works:

  1. Add one to A for each ID in the selector.

  2. Add one to B for each class in the selector.

  3. Add one to C for each element name (tag name).

  4. Read the result as a three-digit number. (It's not really a three-digit number; it's just that in most cases, reading the result as a three-digit number works. Just understand that you can end up with something like 0-1-12, and 0-2-0 is still more specific.)

So, let's look at the specificity of these examples

p {color:red}        <-- a
p.largetext        <-- b
p#largetext        <-- c
body p#largetext        <-- d
body p#largetext ul.mylist        <-- e
body p#largetext ul.mylist  li        <-- f

(a)0 - 0 - 1 specificity=1

(b)0 - 1 - 1 specificity=11

(c)1 - 0 - 1 specificity=101

(d)1 - 0 - 2 specificity=102

(e)1 - 1 - 3 specificity=113

(f)1 - 1 - 4 specificity=114

Each example is a higher specificity that the previous one.

Cascade Rule 4: Sort by order. If two rules have exactly the same weight, the one furthest down the cascade wins.

The Cascade

Specificity is more important than order, so a more specific rule high up the cascade wins out over a less specific one further down.


And that, dear reader, is the cascade and, yes, it is somewhat hard to understand, especially if you have not yet had much experience with CSS. So I now offer you my simplified version of the Cascade rules, which applies in about 98 percent of cases. If you find that something isn't behaving the way you want when you're using this simplified version, refer to the above rules.

    Previous Page
    Table of Contents
    Next Page