Book HomeHTML & XHTML: The Definitive GuideSearch this book

Chapter 8. Cascading Style Sheets

Contents:

The Elements of Styles
Style Syntax
Style Classes
Style Properties
Tag-less Styles: The <span> Tag
Applying Styles to Documents

Style sheets are the way publishing professionals manage the overall "look" of their publications -- backgrounds, fonts, colors, and so on -- from a single page to huge collections of documents. Most desktop publishing software support style sheets, as do the popular word processors. All desktop publishers and graphic designers worth their salt are out there making web pages. So the cry-to-arms was inevitable: "Whaddaya mean HTML has no style sheets?!"

From its origins, HTML focused on content over style. Authors are encouraged to worry about providing high quality information and leave it to the browser to worry about presentation. We strongly urge you, too -- as we do throughout this book -- to adopt that philosophy in your documents, especially those destined for the World Wide Web. Don't mistake style for substance.

However, while use of the <font> tag and related attributes like color produce acute presentation effects, style sheets, when judiciously applied, bring consistency and order to whole document collections, as well as to individual documents. Remember, too, that presentation is for the benefit of the reader. Even the original designers of HTML understood the interplay between style and readability. For instance, readers can quickly identify section heads in a document when they are enclosed in header tags like <h2>, which the modern browsers present in large and often bold type. Style sheets extend that presentation with several additional effects, including colors, a wider selection of fonts, even sounds so that users can even better distinguish elements of your document. But most importantly, style sheets let you control the presentation attributes for all the tags in a document -- for a single document or a whole collection of many documents, and from a single master.

In early 1996, the World Wide Web Consortium put together a draft proposal defining Cascading Style Sheets (CSS) for HTML. This draft proposal quickly matured into a recommended standard, which the commercial browser manufacturers were quick to exploit. In mid-1998, the W3C extended the original specification to create CSS2 which includes presentation standards for a variety of media besides the familiar onscreen browser, along with a several other enhancements.

Up to now, however, no browser or web agent fully complies with the CSS2 standard. Since we realize that eventual compliance with the W3C standard is likely, we'll cover all the components of the standard in this chapter, even if they are not yet supported by any browser. As always, we'll denote clearly what is real, what is proposed, and what is actually supported.

What we can't do is tell you everything the CSS2 standard provides. Like JavaScript, the Cascading Style Sheet standard deserves a Definitive Guide of its own. Rather, we focus here on the elements of style sheets that impact HTML and XHTML in general and the popular GUI-based browsers, Internet Explorer and Netscape Navigator, in particular. These encompass the majority of the CSS2 standard. What's left out are discussions of other media. We tell you how to tailor your documents to other media, but we don't go into the specifics, such as the CSS2 properties that control paging devices like printers or aural style sheets that govern the presentation of content through speech synthesis. Don't get us wrong; these are fascinating and important topics. They just go beyond our charter.

8.1. The Elements of Styles

At the simplest level, a style is nothing more than a rule that tells the browser how to render[47] a particular tag's contents. Each tag has a number of style properties associated with it, whose values define how that tag is rendered by the browser. A rule defines a specific value for one or more properties of a tag. For example, most tags have a color property, the value of which defines the color Netscape or Internet Explorer may use to display the contents of the tag. Other properties include fonts, line spacing, margins, borders, sound volume, and voice, which we describe in detail later in this chapter.

[47]We explicitly avoided the term "display" here because it connotes visual presentation, whereas the CSS2 standard works hard to suggest many different ways of presenting the tagged contents of a document.

There are three ways to attach a style to a tag: inline styles, document-level styles, and external style sheets. You may use one or more style sheets for your documents. The browser either merges the style definitions from each style or redefines the style characteristic for a tag's contents. Styles from these various sources are applied to your document, combining and defining style properties that cascade from external style sheets through local document styles, ending with inline styles. This cascade of properties and style rules gives rise to the standard's name: Cascading Style Sheets.

We cover the syntactic basics of the three style sheet techniques here. We delve more deeply into the appropriate use of inline, document-level, and external style sheets at the end of this chapter.

8.1.1. Inline Styles: The style Attribute

The inline style is the simplest way to attach a style to a tag -- just include a style attribute with the tag along with a list of properties and their values. The browser uses those style properties and values to render the contents of just this instance of the tag.

For instance, the following style tells the browser to display the level-1 header text, "I'm so bluuuuoooo!", not only in the <h1> tag style characteristic of the browser, but also in the color blue and italicized (if the browser is capable):

<h1 style="color: blue; font-style: italic">I'm so bluuuuoooo!</h1>

This type of style definition is called "inline" because it occurs with the tag as it appears in the document. The scope of the style covers the contents of that tag only. Since inline styles are sprinkled throughout your document, they can be difficult to maintain. Use the style attribute sparingly and only in those rare circumstances when you cannot achieve the same effects otherwise.

8.1.2. Document-Level Style Sheets

The real power of style sheets becomes more evident when you place a list of presentation rules within the head of a document. Enclosed within their own <style> and </style> end tags, so-called "document-level" style sheets affect all the same tags within that document, except for tags that contain an overriding inline style attribute.[48]

[48]XHTML-based document-level style sheets get specially enclosed in CDATA sections of your documents. See Chapter 16, "XHTML" for details.

<style>

Function:

Define a document-level style sheet

Attributes:

DIR

LANG

MEDIA

TITLE

TYPE

End tag:

</style>; rarely omitted in HTML

Contains:

styles

Used in:

head_content

The <style> tag must appear within the <head> of a document. Everything between the <style> and </style> tags is considered part of the style rules to be applied to the document. To be perfectly correct, the contents of the <style> tag are not HTML or XHTML and are not bound by the normal rules for markup content. The <style> tag, in effect, lets you insert foreign content into your document that the browser uses to format your tags.

For example, a styles-conscious browser will display the contents of all <h1> tags as blue, italic text in a document that has the following document-level style sheet definition in its head:[49]

[49]This is an HTML example. An XHTML document would enclose styles in a CDATA section instead of in HTML comments. See Section 16.3.7, "Handling Special Characters" for details.

<head>
<title>All True Blue</title>
<style type="text/css">
  <!--
  /* make all level-1 headers blue */
  h1 {color: blue; font-style: italic}
  -->
</style>
</head>
<body>
<h1>I'm so bluuuuoooo!</h1>
...
<h1>I am ba-loooooo, tooooo!<h1/>

8.1.3. External Style Sheets

You may also place style definitions, like our document-level style sheet example for the <h1> tags, into a text file with the MIME type of text/css and import this "external" style sheet into your documents. Because an external style sheet is a separate file and is loaded by the browser over the network, you can store it anywhere, reuse it often, and even use others' style sheets. But most important, external style sheets give you the power to influence the display styles not only of all related tags in a single document, but for an entire collection of documents.

For example, suppose we create a file named gen_styles.css containing the style rule:

h1 {color: blue; font-style: italic}

For each and every one of the documents in our collections, we can tell the browser to read the contents of the gen_styles.css file, which in turn will color all the <h1> tag contents blue and render the text in italic. Of course, that will be true only if the user's machine is capable of these style tricks, they are using a styles-conscious browser like Netscape or Internet Explorer, and the style isn't overridden by a document-level or inline style definition.

You can load external style sheets into your document in two different ways: linked or imported.

8.1.4. Media-Specific Styles

Besides the media attribute for the <style> tag, the CSS2 standard has two other features that let you apply different style sheets depending on the agent or device that will render your document. This way, for instance, you can have one style or whole style sheet take effect when your document gets rendered on a computer screen, and another set of styles for when the contents get punched out on a braille printer. And what about those cell phones on the Web?

Like the media attribute for the style tag that affects the entire style sheet, you can specify whether the user's document processor[50] will load and use an imported style sheet.

[50]A.k.a. "user agent." Web documents get rendered on all kinds of devices these days, including the popular browser, braille printers, televisions, and projectors, to name just a few.

Do that by adding a media-type keyword or a series of comma-separated keywords to the end of the @import at-rule. For instance, the following example lets the user-agent decide to import and use the speech-synthesis style sheet or a common PC display and print style sheet if it is able to render the specified media types:

@import url(http://www.kumquats.com/styles/visual_styles.css) screen,print;
@import "http://www.kumquats.com/styles/speech_styles.css" aural;

The CSS2 media types include all, aural (speech synthesizers, for example), braille (tactile), embossed (braille printers), handheld, print, projection, screen, tty (fixed-width fonts), and tv.

Another CSS2 way to select media is through the explicit @media at-rule, which lets you include media-specific rules within the same style sheet, either at the document level or in an external style sheet. At the document level, like @import, the @media at-rule must appear within the <style> tag contents. And the at-rules may not appear within another rule. Unlike @import, @media may appear subsequent to other style rules, and indeed its style-rule contents may override previous rules according to the cascading standard.

The contents of @media include one or more comma-separated media-type keywords followed by a curly-braces ({}) enclosed set of style rules. For example:

body {background: white}
@media tv, projection	 {
     body {background: lt_blue}
     }

The general style rule for the document's body background color of white gets changed to light blue by the one within the @media at-rule, but only if the document gets rendered on a television or projection system instead of some other medium. (Notice the extra set of curly braces that contain the @media style rules?)

8.1.5. Linked Versus Imported Style Sheets

At first glance, it may appear that linked and imported style sheets are equivalent, using different syntax for the same functionality. This is true if you use just one <link> tag in your document. However, special CSS2-standard rules come into play if you include two or more <link> tags within a single document, even though the current browsers don't abide by the rules yet.

With one <link> tag, the browser should load the styles in the referenced style sheet and format the document accordingly, with any document-level and inline styles overriding the external definitions. With two or more <link> tags, the browser should present the user with a list of all the <link>ed style sheets. The user then selects one of the linked sheets, which the browser loads and uses to format the document; the other <link>ed style sheets get ignored.

On the other hand, the styles-conscious browser merges, as opposed to separating, multiple @imported style sheets to form a single set of style rules for your document. The last imported style sheet takes precedence if there are duplicate definitions among the style sheets. Hence, if the external gen_styles.css style sheet specification tells the browser to make <h1> contents blue and italic, and spec_styles.css tells the browser to make <h1> text red, then the <h1> tag contents will appear red and italic. And if we later define another color, say yellow, for <h1> tags in a document-level style definition, the <h1> tags will all be yellow, and italic. Cascading effects. See?

In practice, the popular browsers treat linked style sheets just like imported ones by cascading their effects. The browsers do not currently let you choose from among linked choices. Imported styles override linked external styles, just as the document-level and inline styles override external style definitions. To bring this all together, consider the example:

<html>
<head>
<link rel=stylesheet href=sheet1.css type=text/css>
<link rel=stylesheet href=sheet2.css type=text/css>
<style>
<!--
  @import url(sheet3.css);
  @import url(sheet4.css);
-->
</style>
</head>

Using the CSS2 model, the browser should prompt the user to choose sheet1.css or sheet2.css. It should then load the selected sheet, followed by sheet3.css and sheet4.css. Duplicate styles defined in sheet3.css or sheet4.css and in any inline styles will override styles defined in the selected sheet. In practice, the popular browsers cascade the style sheet rules as defined in the example order sheet1 through sheet4.

8.1.6. Limitations of Current Browsers

Internet Explorer 4 and Netscape Navigator 4 and beyond support the <link> tag to apply an external style sheet to a document. Neither Netscape Navigator nor Internet Explorer support multiple <link>ed style sheets as proposed by the CSS2 standard. Instead, they cascade all the <link>ed style sheets, with rules in later sheets overriding rules in earlier sheets.

Netscape Navigator ignores all at-rules and their contents, including @import and @media, but does process other style rules that you may include before or after the at-rule within the <style> tag. Internet Explorer honors the @import as well as the @media at-rules, for both document-level and external sheets, allowing sheets to be nested.

Achieving media-specific styles through external style sheets with current Netscape browsers is hopeless. Assume, therefore, that most people who have Netscape will render your documents on a common PC screen, so make that medium the default one. Then embed all other media-specific styles, such as those for print or braille, within @media at-rules, so that Internet Explorer and other CSS-compliant agents will properly select styles based on the rendering medium. The only other alternative is to create media-specific <style> tags within each document. Run, do not walk, away from that idea.

We just hope the CSS2 standard will prevail soon so that style sheets, already mystifying to most, will become at least that much less confusing.

8.1.7. Style Comments

Comments are welcome inside the <style> tag and in external style sheets, but don't use standard HTML comments; style sheets aren't HTML. Rather, enclose style comments beginning with the sequence /* and ending with */, as we did in the example in Section 8.1.2, "Document-Level Style Sheets". (Those of you who are familiar with the C programming language will recognize these comment markings.) Use this comment syntax for both document-level and external style sheets. Comments may not be nested.

We recommend documenting your styles whenever possible, especially in external style sheets. Whenever the possibility exists that your styles may be used by other authors, comments make it much easier to understand your styles.

8.1.8. Handling Style-less Browsers

In our document-level style examples, you probably noticed that we placed the style definition inside a comment tag (<!-- and -->). That's because although the older, style-less browsers will ignore the <style> tag itself, they will display the style definitions. Needless to say, your documents will not go over well when the first half of the display contains all your style rules.

The newer, styles-conscious browsers ignore HTML comments within a <style> tag. Style-less browsers may be with us for some time to come, so it's probably best to place your document-level style rules inside comments. HTML comments should not be used in external style sheets.

For XHTML, document-level styles must be enclosed in a CDATA section instead of in HTML comments. See Section 16.3.7, "Handling Special Characters" for details.

8.1.9. Style Precedence

You may import more than one external style sheet and combine them with document-level and inline style effects in many different ways. Their effects cascade (hence, the name, of course). You may specify the font type for our example <h1> tag, for instance, in an external style definition, whereas its color may come from a document-level style sheet.

Style sheet effects are not cumulative, however: of the many styles which may define different values for the same property -- colors for the contents of our example tag, for instance -- the one that takes precedence can be found by following these rules, listed here in order.

Sort by origin

A style defined "closer" to a tag takes precedence over a more "distant" style. So an inline style takes precedence over a document-level style, which takes precedence over the effects of an external style.

If more than one applicable style exists, sort by class

Properties defined as a class of a tag (see Section 8.3, "Style Classes") take precedence over a property defined for the tag in general.

If multiple styles still exist, sort by specificity

The properties for a more specific contextual style (see Section 8.2.3, "Contextual Selectors") take precedence over properties defined for a less specific context.

If multiple styles still exist, sort by order

The property specified latest takes precedence.

The relationship between style properties and conventional tag attributes is almost impossible to predict. Style sheet-dictated background and foreground colors -- whether defined externally, at the document level, or inline -- override the various color attributes that may appear within a tag. But the align attribute of an inline image usually takes precedence over a style-dictated alignment.

There is an overwhelming myriad of style and tag presentation-attribute combinations. You need a crystal ball to predict which combination wins and which loses the precedence battle. The rules of redundancy and style versus attribute precedence are not clearly elucidated in the W3C CSS2 standard, nor is there a clear pattern of precedence implemented in the styles-conscious browsers. This is particularly unfortunate since there will be an extended period, perhaps several years, in which users may or may not use a styles-conscious browser. Authors will have to implement both styles and non-style presentation controls to achieve the same effects.

Nonetheless, our recommendation is to run -- as fast as you can -- away from one-shot, inline, localized kinds of presentation effects like those afforded by the <font> tag and color attribute. They have served their temporary purpose; it's now time to bring consistency (without the pain!) back into your document presentation. Use styles. It's the HTML way.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.