User:Bartlett/07

Ka Wiktionary

Hour 7. Cascading and Inheritance[wax ka badal]

What You'll Learn in This Hour:
  • What the secret formula behind the cascade really is
  • Which CSS rules have the highest weight, and how those relate to HTML attributes
  • How you can override the order of the cascade when writing CSS rules
  • How the user can supply her own style sheet to express her preferences for display, and how those are balanced with the author's desires
  • How to include one style sheet's rules within another style sheet, and which set of rules takes priority
  • Which property values are inherited, which are calculated, and what that means for your CSS designs

The cascade is one of the key concepts of Cascading Style Sheetsso important, in fact, that the language was named after it. The cascade defines how you combine rules, including rules from different sourcessome provided by the web developer, some by the browser, and some from the user. When these are combined, values for properties on individual HTML tags are calculated. Some of these take their values directly from the CSS rules, whereas others are derived from other properties.

./ ADD NAME=CH07LEV1SEC1.HTML

How the Cascade Works[wax ka badal]

The cascade is the set of directions that determine what rules apply to a given element on the page. Without a method for determining priority of conflicting rules, it would be impossible to figure out which styles should be used. Take, for example, the style sheet shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07ex01 Listing 7.1]different rules with a number of different selectors.

Listing 7.1. A Colorful Style Sheet
/* colors-7.1.css */<br /><br />body { background-color: white;<br />color: black; }<br /><br />h1 { background-color: blue;<br />color: red; }<br /><br />em { background-color: green;<br />color: black; }<br /><br />#serious { color: purple; }<br /><br />.yahoo { color: black;<br />background-color: yellow; }<br /><br />#serious { color: maroon; }<br /><br />h1 em { color: lime; }<br />

Now you'll look at a page that uses the style sheet and also has its own embedded CSS rules within a <style> element in the <head>. Such a page is listed in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07ex02 Listing 7.2].

Listing 7.2. An HTML Page with Tips on Color Use
<!-- tips-7.2.html --><br /><html><br /><head><br /><title>Accessibility of Color</title><br /><link type="text/css" rel="stylesheet" href="colors-7.1.css"><br /><style type="text/css"><br />.yahoo { background-color: silver;<br />color: white; }<br />h1 { background-color: yellow; }<br /></style><br /></head><br /><body><br /><h2>Accessibility Tip:</h2><br /><h1>Don't<br /><em class="yahoo" id="serious"<br />style="background-color: white;">Rely</em><br />on Color Alone</h1><br /><p> Some Web users may be unable to see color -- they may<br />be blind (and use a screenreader program); they may<br />be color-blind and unable to easily distinguish colors;<br />or they could be using an access device, such as a cell<br />phone, which does not display color. For this reason,<br />the W3C's Web Accessibility Initiative recommends that<br />you not <em>rely</em> upon color as the <em>only</em><br />way of conveying information.</p><br /><p style="color: navy;">This doesn't mean<br /><em class="yahoo" style="color: red;">"don't use color"</em><br />-- on the contrary,<br />color is very useful to those who can see it, and will<br />help make your page understandable. What it does mean<br />is that color (and other presentational effects) should<br />not be the only way you make something special. For<br />example, rather than use a <span> and a color<br />style to make something stand out, use the <strong><br />tag (which you can also style) so browsers that<br />can't use the visual CSS color rule can at least know<br />to emphasize that section -- perhaps by increasing the<br />volume when reading the text out loud, for example.</p><br /></body><br /></html><br />

Now concentrate on the second word in the headline, "Rely." This word is within an element, which is part of an

. It has a class of yahoo and an id of serious. What color will the text be, and what color background will it have? You have several choices from several sources; by using the cascade, you can figure out what a browser will do with your example. In [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07table01 Table 7.1], I've listed the various sources from which the browser might find the background and foreground color for the word "Rely."
Color Background Selector Source
black white body Linked style sheet
red blue H1 Linked style sheet
black green em Linked style sheet
purple #serious Linked style sheet
black yellow .yahoo Linked style sheet
marooon #serious Linked style sheet
lime h1 em Linked style sheet
white silver .yahoo Embedded style sheet
yellow H1 Embedded style sheet
white (implied) Inline style element
Order of the Cascade 

To be able to figure out which properties get applied to the tag in your example, you need to think like a web browser. The first thing you need to do is to realize that many of your rules are combined rules. For example, take this rule:

.yahoo { color: black;
 background-color: yellow; }

The rule is actually two different rules, which happen to share a common selector, as follows:

.yahoo { color: black; }
.yahoo { background-color: yellow; }

This is important because each declaration (property name and value) could be overridden separately. A rule that changes the color might not change the background color at all, so the .yahoo background-color rule would continue to stay in effect even if the .yahoo color rule is superceded.

So you need to consider only those rules that are in conflictin other words, those that designate different values for the same property name, such as those rules that affect the color property. When trying to analyze which rule takes priority, always break up rules in individual units as just shown.

How do you calculate which rule is applied? First, you sort these rules by their origin. In the cascade, the origin means one of the following: the author of the page, the user, or the browser. Author rules have priority over user rules, which have priority over the browser's default rules for how to display HTML elements. In this case, all of these rules have the same origin; they come from the author of the page.

Next you order the rules based on the selector and how specific it is. This specificity is calculated as follows:

#
An inline style attribute is the most specific type of rule. If there is an inline style rule for a specific CSS property, that rule "wins."
  1. An id selector is the second most specific. If there is more than one id in the rule, the rule with greatest number of id selectors wins.
  2. If there aren't any id selectors, or if there's the same number, count the number of classes or pseudo-classes in the rule. The rule with the most classes or pseudo-classes has the higher priority.
  3. If there's the same number of classes (or no classes), compare the number of elementsthe greater number of elements, the higher the specificity.
  4. If the number of id values, classes, and elements are all the same, whichever was declared most recently has the highest priority. If two rules have the same selector and are in disagreement on the value of a specific CSS property, the one listed second is more specific.

If you ever encounter a tie, then move on to the next rule. For example, if you have a complex rule that has three id selectors, three class selectors, and two element selectors, and another with three id selectors, three class selectors, and one element selector, you have a tie for the id selectors, and a tie for the class selectors, so to resolve the cascade you need to move on to the number of elements to break the tie.

Applying these rules to your text, you must consider the color property separately from the background-color property. The most specific rules that set the color property are the two rules with an id selectorthe #serious rules. Of these, the second one takes priority, which means the text color will be maroon.

To figure out the background-color, you just have to determine the most specific rule as well. In this case, the most specific rule is the inline style attribute, so the background will be white.

Calculating the colors of the

is also a useful illustration; you have two competing

selectors: one in the linked style sheet and one in the embedded style sheet. Which one triumphs? The one declared most recently; because your <style> comes after your <link>, the background-color will be yellow. If the order of the <link> and <style> elements were reversed, the background would be blue.
Try it Yourself: Pretend to Be a Web Browser

Here's your chance to show how good you are at imitating a web browser. In [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07ex01 Listing 7.1], there's a section in the second paragraph that reads "don't use color."

1.
Construct a table like [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07table01 Table 7.1]. List the selector, the source, the color, and the background color of each rule that applies to that section of text.

2.
For each rule, identify whether it comes from a style attribute, an id selector, a class (or pseudo-class) selector, an element selector, or a combination of these.

3.
Rank each selector according to the specificity, as described this hour.

4.
What color will the text be? Test it in your web browser to check your answer.

Cascading and HTML Attributes 

In addition to setting style, class, and id attributes, HTML also has presentational attributes that let you affect how the page looks. Examples include align, color, face, link, vlink, bgcolor, and background.

When these attributes conflict with a CSS rule, the HTML attribute is considered to be the least specific declaration possible. In other words, the HTML attribute always is overridden by a CSS rule. However, in many cases you may want to set an HTML presentation attribute in case CSS is disabled or not understood by an older browser. Keep in mind that HTML presentational attributes are ignored only if there is a corresponding CSS rule; if there's no rule setting the color of an item, for example, the HTML value is used.

Did you Know? Remember, you generally can't use HTML presentation attributes with CSS if you are using the Strict variety of HTML. Use HTML 4.01 Transitional (or XHTML 1.0 Transitional) if you need to use HTML attributes along with your CSS styles.
 Using !important in Rules 

When necessary, an author of a style sheet can designate one rule as explicitly more important than others. To do this, the author adds !important after the specific property name and value declaration, like this:

em { color: blue !important; }

This overrides the normal order of the cascade by inserting a new requirement: Important rules come before rules that have not been designated as important. An !important rule, even one that is not very specific, always takes priority over a non-!important rule even if the latter is extremely specific.

The use of !important also changes one other part of the cascade: !important rules that originate with the user take priority over the author's rules. Normally, the author's rules have higher priority than the user's rules, but this allows users with special needs to define their own style sheets and designate their needs for access as more important than the author's desire for a certain style.

Watch Out! Those of you who have done programming in a language such as C++ or Perl may find this particular part of CSS perplexing. In most programming languages, an exclamation point (!) means "not," so !important looks like it means "not important," which is the exact opposite of the true meaning. Don't be surprised if it takes a while to get used to reading !important as "very important."
./ ADD NAME=CH07LEV1SEC2.HTML

User-Defined Style Sheets

A user-defined style sheet is one created by the user and stored on that person's local computer. The browser automatically loads this file and applies it to web pages that are viewed.

The purpose of a user-defined style sheet is to let the web surfer's preferences influence how he views the web. This is especially useful for certain specific groups of users, including those users with visual disabilities. For example, if you need a high-contrast display, your user style sheet could be set with a default black background, white text, and large font sizes.

In theory, user style sheets are quite beneficial; in practice, though, they require each web user to know how to write CSS to see the web the way she would like to see it! This is a rather high learning threshold for users who simply want to surf the web comfortably; you're learning CSS now because you want to design websites, not because you simply want to access information. Despite this, user style sheets are still incredibly functional for those who know how to use them, or for those who can download and install user style sheets written by others.

A user style sheet can have any kind of CSS rules that could normally be included in a style sheet, and the syntax is exactly the same; it's just another external style sheet, after all. However, there are certain types of rules that make less sense in a user style sheet, and several normal cautions can be relaxed.

In a user style sheet, you don't want to use any selectors that presume specific attribute values will be set, such as class or id, because you won't know what's in the HTML of each page.

Normally when creating a style sheet, you don't want to use absolute values in your font sizes, such as 9px or 2cm, because these don't take the user's preferences into account. A user with poor vision would have problems seeing a 9-pixel font size if you put this on a style sheet for the web. But because you know the exact properties of the final output medium when writing a user-defined style sheet for yourself, it's perfectly fine to use those values in your own user-defined style sheet.

Finally, you should declare these as !important to give them highest priority because, after all, it doesn't make sense to set your own preferences if the designer's style sheet can just overrule them.

An example of a user-defined style sheet is given in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07ex03 Listing 7.3]. This style sheet is designed specifically for a user who needs large print and high contrast (white-on-black).

Listing 7.3. A Sample User-Defined Style Sheet
/* user-7.3.css */<br />* { color: white !important;<br />background-color: white !important;<br />font-family: Verdana, sans-serif !important; }<br />body { font-size: 24pt !important; }<br />a:link { color: cyan !important; }<br />a:visited { color: violet !important; }<br />

After you've created a user-defined style sheet and saved it on your hard drive (somewhere you can remember its location), you need to tell your browser to use it. How you do that depends on which browser you're using. In Internet Explorer, this is a preference under Accessibility. If you're using Firefox, you need to add your rules to the user.css file. In Opera, this is a preference under Document that lets you select a user-defined style sheet. It's an Advanced preference in Safari.

./ ADD NAME=CH07LEV1SEC3.HTML 

Importing CSS[wax ka badal]

To make style sheets that are more modular, you may want to import another style sheet. Importing, in this context, means that all the rules in the imported style sheet are included in the style sheet that is doing the importing. In this way, importing is like linking an external style sheet.

You can import another style sheet from an embedded style sheet, from a linked style sheet, or from a user style sheet. An imported style sheet can even import additional style sheets.

How do imported style sheets affect the cascade order? You might think that rules are included at the point where the importation is declared, but this actually isn't the case. Any imported style sheets are treated as if their rules had been declared before any of the rules in the importing style sheet.

You can think of the imported style sheet as being more distant, which means it is lower priority if there is a conflict. All other things being equal (same number of id attributes, classes, and elements), the importing style sheet's rules are considered more recently declared, even if the rule happens before the importation.

By the Way If you're designing a large website, and some CSS rules apply to the whole site, whereas others should be used only with certain sections of the site, you may want to write one site-wide style sheet and then import it into the style sheets you write for each part of the site.
 The @import Rule 

To import a file, you write as a complete rule (with no property declarations or curly braces) an @import statement that looks like this:

@import url("filename.css");

An alternate way to write the same rule is to leave out the url() function because everything you will @import will be a URL. So you can also write the rule like this:

@import "filename.css";

You can also give @import an extra parameter, which is a list of media types. Like the media attribute on the <link> attribute, the style sheet loads only if the media type is correct for the browser being used. For example:

@import "screenorprint.css" screen, print;
@import "allmedia.css" all;

Here's an example of @import in action. First, the importing style sheet:

h1 { color: red; }
h1, h2, h3, h4, h5, h6
 { font-family: sans-serif; }
@import "sitewide.css";
h2 { color: blue; }

And here's the imported style sheet:

/* sitewide.css */
h1, h2, h3, h4, h5, h6
 { color: green; }
body { background-color: silver; }
What color is an

,

, or

on a page using the importing style sheet? The

would be red and the

would be blue because all the imported rules are considered to come before the original style sheet's rules. The

would be green because that's the only rule setting its color.
Did you Know?

The old, nearly extinct Netscape 4 browser didn't understand the @import rule; it simply wouldn't import other style sheets. This flaw actually got put to good use by web developers, to hide other rules that Netscape 4 couldn't understand. (It was a browser with lots of CSS problems.) All rules that were "Netscape 4 safe" could be put in the main CSS file, and then an additional style sheet could be @imported that contained style rules that would break in Netscape 4 but worked in other then-contemporary browsers.

This was the first browser filter ever developed. You'll learn more about filtering and other tricks in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch24.html#ch24 Hour 24], "Troubleshooting and Browser Hacks."
./ ADD NAME=CH07LEV1SEC4.HTML 

Inheritance

As you've already seen, some property values don't have to be explicitly set on each element if the value is already set on a parent element. For example, if you set a font-family property on the <body>, all other elements on the page will also have the same value unless it's changed by another rule. This is called inheritance; the page elements have inherited the property value from their parent element, <body>.

Not all properties inherit naturally; some simply don't make sense for inheritance. For example, the border, margin, and padding properties from [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch06.html#ch06 Hour 6], "The CSS Box Model," don't inherit. Otherwise, whenever you'd draw a box, all elements inside it would have the same type of box around them. Each property, when it's defined in the CSS specifications, is designated as either inheriting or not inheriting, by default.

 Inherited Values 
An inherited value is passed along in most cases as if it had been set on the element itself. Thus, if you make an

blue, you're making all its children blue because they'll inherit the color. Other rulesmore specific or higher prioritycould change this, of course. Of the properties you've learned so far, font-family and color are inherited. The display, border, margin, and padding properties are not inherited. You might think that background-color is inherited, but actually it's not; the default when background-color is unset is actually the special value TRansparent, which means the color "underneath" can be seen, so it's not quite the same as inheriting the value. Calculated Values The font-size property works a little differently when it comes to inheritance. That's because you don't actually inherit the declaration; you inherit the calculated value. Some values are absolute values, such as 12px, but most will be relative values, such as smaller or 3em. When a relative value is inherited, the value is first calculated before being passed on to child element. Specifying Inheritance If you want a property to inherit from its parent, but it doesn't actually do so by default, you can use the special value of inherit in a rule you write. Say that you decide any
in the class standout should have a blue border and that any paragraphs inside it should have the same border. You could write these rules:
div.standout { border: 1px solid blue; }
div.standout p { border: inherit; }
./ ADD NAME=CH07LEV1SEC5.HTML 

Summary

In this hour, you learned about the cascade, user style sheets, importing style sheets, and inheritance.

The cascade first sorts rules based on source: Author style rules take priority over user style rules, which take priority over browser default styles. After that, the more specific a rule, the higher priority it's given. You can add !important to a rule to give it a higher priority.

User style sheets are a crucial part of the cascade that allows the user's preferences to blend with the author's desires. Users with disabilities can often benefit from specific style sheets tailored to their needs.

Not all values need to be explicitly set; values can be inherited from their parent element. Some properties inherit, and some don't; those that use relative values pass along the calculated value.

./ ADD NAME=CH07LEV1SEC6.HTML 

Workshop[wax ka badal]

The workshop contains a Q&A section, quiz questions, and activities to help reinforce what you've learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.

 Q&A
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07qa1q1a1 Q.] Why is it a big deal that calculated values are inherited, instead of relative values?
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07qa1q1 A.] Well, consider this example:
<div class="footer"><br /><p><br />Questions? Send me email at<br /><a href="mailto:kynn@idyllmtn.com"><br />kynn@idyllmtn.com<br /></a><br /></p><br /></div><br />

If the font on the page is 20 pixels, and the style rule is div.footer { font-size: smaller; }, text elements within the
inherit the calculated value 16 pixels, which is 20% smaller than 20 pixels. The elements within the
do not inherit the relative value smaller. What if the text elements did inherit the relative value? Well, then the

would have to be 20% smaller than the size of the

(about 12.8 pixels). The <a> would inherit smaller from its parent and would shrink to 80% of the

, so the email address would be 10.24 pixelsincredible shrinking text! This is why calculated values are not inherited.

[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07qa1q2a2 Q.] How did the order of the Cascade change between CSS Level One and CSS Level Two?
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07qa1q2 A.] When CSS Level One was published, the author's !important styles took precedence over the user's !important styles. This was found to be a problem because it meant that users with special needs had no way to insist that the browser meet their needs. In the CSS Level Two recommendation, this was changed so that the user's !important rules beat the author's !important rules. Note that this is a special case exception; in most cases, the author's styles override the user's styles, assuming the user's styles are not flagged as !important.
Quiz
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07qa2q1a1 1.] Rank these CSS rules in order from least specific to most specific:
#
p { font-family: serif; }
  1. p#mocha { font-family: monospace; }
  2. TR td p { font-family: sans-serif; }
  3. TD p.latte { font-family: cursive; }
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07qa2q2a2 2.] How would your answer to question 1 change if rule (a) were rewritten like this?
#
p { font-family: serif !important ; }
Answers
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07qa2q1 1.] The least specific is (a): It has no id selectors, no classes, and only one element. Rule (d) is more specific because it has three elements instead of one. Rule (e) is more specific than (d), even though it has only two elements, because (e) has one class and (d) has none. Rule (c) is less specific than Rule (b) because id selectors are less specific than inline styles. Therefore, a paragraph that was affected by all these rules would be in a fantasy font.
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch07qa2q2 2.] The addition of !important to rule (a) makes it more important than the others, and thus the font-family value would be serif. However, the specificity technically did not change; it is still less specific than the others, although it has higher priority. So it's a bit of a trick question; the priority would change, but because question 1 asked you about specificity, not priority, your answer should not change.
Exercise 

One of the best ways to become familiar with the cascade is to set up your own user style sheet. Create your own style sheet, save it on your hard drive, and tell your browser to use it as a user style sheet. You can experiment with !important and other aspects of the cascade by changing your user style sheet.

./ ADD NAME=CH08.HTML