Section 16.6. Key Concepts


16.6. Key Concepts

To become comfortable with the way CSS behaves, it is important to have an understanding of its guiding concepts . This section provides a basic introduction to these fundamental ideas:

  • Document structure and inheritance

  • Conflicting style rules: the "cascade"

  • Element types

  • The box model

16.6.1. Document Structure and Inheritance

XML, XHTML, and HTML documents have an implicit structure or hierarchy. For instance, the html root element usually contains a head and a body, and the body, in turn, contains some number of block-level elements, such as paragraphs (p). A paragraph may include inline elements such as anchors (a) or emphasized text (em). This hierarchy can be visualized as a tree, branching out from the root. Figure 16-2 shows the document tree structure of a very simple XHTML document.

Figure 16-2. Document tree structure


16.6.1.1. The parent-child relationship

The document tree becomes a family tree when it comes to referring to the relationship between elements. An element that is directly contained by another element is said to be the child of that element. In Figure 16-2, the p element is the child of body, and body is said to be its parent. Elements that have the same parent are called siblings . In the example, the li element is the child of ol, its parent, and the other li elements are its siblings. This parent-child relationship is fundamental to how CSS works.

Notice in the example that the p element contains an a element, which in turn contains the inline element strong. Technically, the strong element is contained by the p element as well. All the elements a given element contains are said to be its descendants . To be considered a child, an element needs to be directly under its parent element in the hierarchy (therefore, a child is just a special kind of descendant). As you might expect, the terminology extends in the other direction as well, as all elements higher than a particular element in the hierarchy are known as its ancestors. The root element is called the root element because it has no ancestors.

This may all seem academic, but as you'll see, an awareness of the structure tree of your document comes into play in practical ways when working with CSS.

16.6.1.2. Inheritance

Related to structural relationships is the concept of inheritance, in which most styles are passed down from an element to its descendants. In other words, a child may inherit property values from its parent. For example, if a style rule applies a text color to a ul list, then every list item (li) within that list will be that color as well, because they inherit the property from their parent element. In CSS, most properties are inherited , but some (such as margins and backgrounds) are not. Inheritance is noted in the property descriptions throughout this book.

Styles applied to specific elements override settings higher in the hierarchy. With planning, inheritance can be used to make style specification more efficient. For example, if you'd like all the text on the page to be blue except for list items, you can set the color property at the body level to apply to the whole document and then use another rule to make lis a different color.

This notion of some rules overriding others brings us to an important concept: the cascade .

16.6.2. Conflicting Style Rules: The Cascade

It is possible (even common) for elements in a document to get presentation instructions from several sources. Conflicts are certain to arise. The working group that developed CSS anticipated this situation and devised a hierarchical system that assigns different weights to various sources' style information. The cascade (of Cascading Style Sheets) refers to what happens when several sources of style information vie for control of the elements on a page; style information is passed down until it is overridden by a style command with more weight.

The cascade order provides a set of rules for resolving conflicts between competing style sheets. When a user agent (such as a browser) encounters an element, it looks at all of the style declarations that might possibly apply to it, and then sorts them all out according to style sheet origin, selector specificity, and rule order to determine which one applies.

16.6.2.1. Style sheet origin

At the top level, user agents look at the origin of the style declarations. Browsers give different weight to style sheets from the following sources, listed from the least weight to greatest:


User agent style sheets

This is the style information that is built into the browsing device for rendering HTML elements and sets their default appearance.


Reader style sheets

The reader (or user) may also create a style sheet. Reader style sheets override the default browser styles.


Author style sheets

When the author of a document attaches a style sheet to it, those declarations take precedence over the reader and user agent style sheets (with an "important" exception, listed next).


Reader !important style declarations

In CSS 2, reader style declarations marked as !important (see the sidebar "Assigning Importance") trump all style declarations, even those from author style sheets.

In CSS 1, any style marked as "important" by the author took precedence over all reader styles. This was reversed in CSS 2.


After considering the source of the style sheet, there is another hierarchy of weights applied to style sheets created by the document's author. As discussed in this chapter, authors may attach style information to documents as inline styles, an embedded style element, or one or more external style sheets. These points of origin within the author style sheets are given varying weights as well (remember, all author styles override reader and user agent styles unless the reader marks a style !important). The following list indicates the weight of various author style declarations, from least to most weight. In other words, style rules farther down in the list override those higher in the list.


Linked external style sheets (using the link element)

If there are multiple linked style sheets, the style rules in style sheets listed lower in the document take precedence over those listed above it. For example, if an HTML document links to two style sheets, like this:

     <head>     <link rel="stylesheet" href="style1.css" type="text/css" />     <link rel="stylesheet" href="style2.css" type="text/css" />     </head> 

Assigning Importance

If you want a rule not to be overridden by a subsequent conflicting rule, include the !important indicator just after the property value and before the semicolon for that rule. For example, to always set all paragraph text to blue, use the following rule in a style sheet for the document:

     p {color: blue !important;} 

Even if the browser encounters an inline style later in the document (which should override a document-wide style sheet), like this one:

     <p style="color: red"> 

that paragraph will still be blue, because the rule with the !important indicator cannot be overridden by other styles in the author's style sheet.

The only way an !important rule may be overridden is by a conflicting rule in a reader (user) style sheet that has also been marked !important. This is to ensure that special reader requirements, such as large type for the visually impaired, are never overridden.

Based on the previous style examples, if the reader's style sheet includes this rule:

     p {color: black;} 

the text would still be blue, because all author styles (even those not marked important) take precedence over the reader's styles. However, if the conflicting reader's style is marked !important, like this:

     p {color: black !important;} 

the paragraphs will be black and cannot be overridden by any author-provided style.


If a style rule provided in style2.css conflicts with a style rule in style1.css, the rule located in style2.css will take precedence because that style sheet is listed lower in the source document.


Imported external style sheets (using @import)

Imported style information overrides linked styles. If there are multiple @import directives, the rules provided in the style sheets lower in the list override the ones above.


Embedded style sheets (with the style element)

Styles applied to a specific document override those set externally.


Inline styles (using the style attribute in an element tag)

Inline styles override all other style declarations that may reference that element, with one exception.


Style declarations marked as !important

Any style marked as !important overrides all other conflicting style rules. The only thing that can override an important rule in an author style sheet is an important rule created by the user (as noted earlier).

16.6.2.2. Selector specificity

So far, we've looked at the priorities given to various sources of style information and methods for attaching style to markup. Once the set of applicable style rules has been chosen, there may still be conflicts. For this reason, the cascade continues at the rule level.

In the following example, there are two rules that reference the strong element.

     strong {color: red;}     h1 strong {color: blue;} 

The user agent assigns different levels of weight to the various selector types. The more specific the selector, the more weight it is given to override conflicting declarations. In the previous example, all the strong text in the document will render in red. However, if the strong text appears within a first-level heading, it will be blue instead, because an element in a particular context is more specific and carries more weight than the element alone.

The following is a list of selector types in order by weight from least to most. The selector types and terminology are explained in Chapter 17.

  • Individual element and pseudoelement selectors (e.g., p, or :first-letter)

  • Contextual selectors (e.g., h1 strong)

  • Class selectors (e.g., p.special)

  • ID selectors (e.g., p#intro)

Keep in mind that any rule marked !important will override conflicting rules regardless of specificity or order.

16.6.2.3. Rule order

Finally, once styles have been sorted by author, attachment method, and specificity, there may still be conflicts within a single style sheet source. When a style sheet contains several conflicting rules of identical weight, whichever one comes last has the most weight and overrides the others in the list. For instance, in the following example, all of the first-level headings in the document would be red, because the last rule wins.

     h1 {color: green;}     h1 {color: blue;}     h1 {color: red;} 

This "last-one-listed wins" scenario was mentioned earlier in relation to multiple link elements and @import commands. It also applies within a single declaration block. In the following example, the first declaration makes the border on all sides of a div gray using the shorthand border-color property. The second declaration conflicts with the first by specifying that the top border should be black. Because the declaration listed second overrides the first, the resulting div will have a black top border and gray borders on the three remaining sides.

Calculating Specificity

There is more to the story of how specificity is determined. The W3C developed a numbering system that expresses a selector's weight value in four parts (a, b, c, d), in which each part is a tally of the selector's particular components:

  • a equals 1 if the rule is a style attribute value rather than a selector. For rules using selectors, a=0. In this way, inline styles will always win out over embedded or external style sheets.

  • b equals the number of ID attributes given in the selector.

  • c equals the number of class attributes, attribute selections, or pseudoclasses in the selector.

  • d equals the number of every element and pseudoelement in the selector.

Here are a few simple examples to show specificity calculation at work. These rules are listed in order from least to most weight:

  • p {color: #FFFFFF;}: One element selector (0,0,0,1)

  • ol li em {color: red;}: Three element selectors (0,0,0,3)

  • .hot {color: red;}: One class selector (0,0,1,0)

  • #tip em {color: blue;}: One ID selector, one element selector (0,1,0,1)

Weight is calculated from left to right, so the last example (#tip em) with a 1 in the b slot would have more weight than the second example (p em) with a 3 in the d slot. That means if there were an em element that matched both these rules, it would be blue, because the selector with the 0,1,0,1 weight value wins.

For more information on calculating selector specificity , see the CSS Recommendation at www.w3.org/TR/CSS21/cascade.html#specificity. Eric Meyer provides a lengthier, illustrated explanation in his book Cascading Style Sheets: The Definitive Guide (O'Reilly).


     div#side {border-color: gray;              border-color-top: black; } 

16.6.3. Block and Inline Elements

If you are familiar with (X)HTML, you already know something about block-level and inline elements . CSS uses the terms "block" and "inline" as well, but it is important to understand that it is not the same as what makes elements either block or inline in (X)HTML.

In (X)HTML, the distinction between block-level and inline elements is based on containment rules, or in other words, what elements can be nested within what other elements. In general, block-level elements may contain both block and inline elements , while inline elements may contain only data and other inline elements. Paragraphs (p), headings (such as h1), lists (ol, ul, dl), and divs are the most common block-level elements . However even some of those block-level elements must obey special rules in (X)HTML; e.g., paragraphs, headings, and address (<address>) may only contain inline elements and content. Emphasized text (em) and anchors (a) are examples of common inline elements. It is invalid markup to nest a paragraph within an anchor element, for example.

In CSS, however, the notion of block-level and inline is purely presentational. block and inline are two possible display roles that are used to tell user agents how to present the element in the layout. Display roles are assigned using the display property. The following descriptions summarize the presentational differences between block-level and inline elements in CSS.

A CSS block-level element (display: block) always generates breaks before and after itself. It fills the available width of the parent element that contains it, whether it's the full width of the body of the document or a smaller defined space like a sized div. You can't place anything next to a block element in the normal flow of the document.

CSS Inline-level elements (display: inline) do not generate any line breaks. They appear in the flow of the line and will break only when they run out of room, at which point they wrap onto a new line.

Unlike the XHTML notions of block and inline, a CSS block-level element may be nested inside an inline-level element and vice versa. Using CSS, any (X)HTML (or XML for that matter) element may be made block-level or inline-level.

There are other values for the display property. The most commonly used and well supported is none, which causes the element not to display at all and essentially removes it from the document flow. Other values include list-item (like a block item, only it displays a number or bullet), run-in (makes an otherwise block element, like a heading, run into the following element, like a paragraph), and a collection of table-related display roles. Table display values are discussed in Chapter 22.

It is worthy of note that elements defined as block-level elements in (X)HTML typically also have a default presentation of display: block when rendered in browsers. Likewise, the default display role of HTML inline elements is display: inline. It is possible to override the default display roles of (X)HTML elements using the CSS display property. In fact, making list items (li) display inline instead of block-level (their default) is a common web design practice (see Chapter 24).

However, bear in mind that changing the presentation of an HTML element with CSS does not change the definition of that element as block-level or inline in HTML. Putting a block-level element within an inline element will always be invalid (X)HTML, regardless of the display role.

While (X)HTML elements have default display roles, elements in other XML languages typically do not. The display property is the tool authors may use to explicitly declare display roles for individual elements.

Authors are advised not to reassign display roles for table-related (X)HTML elements.

Having an awareness of an element's display role is useful for understanding the CSS box model, discussed in the next section.

16.6.4. Introduction to the Box Model

The box model forms the cornerstone of the CSS visual formatting system. It is a critical concept for understanding how style sheets work. This section provides only a basic introduction to the box model. The specifics of applying styles and laying out pages using the box model are provided in Chapters 19 and 21.

According to the box model, every element, whether block or inline, generates a rectangular box around itself called an element box (although block and inline boxes are handled somewhat differently). Properties such as borders, margins, and backgrounds (among others) can be applied to an element's box. Boxes can also be used to position elements and lay out the page. Figure 16-3 shows the resulting boxes for this small sample of markup.

     <body>     <h1>Headline</h1>     <p>This is a paragraph of text. <em>Lorem ipsum </em> dolor sit amet, consecteteur adipiscing elit. Praesent tellus ante, laoreet in, ultrices at, vehicula ut, leo. <strong>Vivamus velit. </strong> Nullam massa odio, condimentum ut, porttitor in, suscipit eu, risus.</p>     <ul>        <li>This is a list of list items</li>        <li>And another item</li>        <li>And another item</li>     </ul>     </body> 

Figure 16-3. XHTML elements and their resulting boxes


Element boxes are made up of four main components. At the core of the box is the element's content. The content is surrounded by some amount of padding, then the border, which is surrounded by the margin, as shown in Figure 16-4.

There are a few fundamental characteristics of the box model worth pointing out:

Figure 16-4. Structure of an element box


  • Padding, borders, and margins are optional. If you set their values to zero, they are effectively removed from the box.

  • The padding area is the space between the edge of the content area and the border (if there is one). Any background color or image applied to the element will extend into the padding area.

  • Borders are generated by style properties that specify their style (such as solid or dashed), width, and color. When a border has gaps, the background color or image shows through those gaps. In other words, backgrounds extend behind the border to its outer edge.

  • Margins are always transparent, which means that the background color or pattern of the parent element will show through. The boundary of the margin (the element's outer edge) is not visible, but is a calculated amount.

  • The width of an element applies to the width of the content area only. This means that when you specify that an element should be 200 pixels wide, the actual contents will display 200 pixels wide, and the cumulative widths of the padding, border, and margins will be added to that amount. (Internet Explorer 5 for Windows is notorious for implementing the width of the box incorrectly. See Chapter 25 for details.)

  • The top, right, bottom, and left sides of an element box may be styled independently of one another. For example, you can add a border to only the bottom of an element, or to only the left and right sides.

This should get you started visualizing your document according to the CSS model, but it's only the beginning. To put these ideas into practical use, see the box properties and positioning discussions in Chapters 19, 21, and 24.




Web Design in a Nutshell
Web Design in a Nutshell: A Desktop Quick Reference (In a Nutshell (OReilly))
ISBN: 0596009879
EAN: 2147483647
Year: 2006
Pages: 325

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net