9. Cascading Style Sheets
Contents:
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 supports 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 earliest 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 HTML documents, especially those destined for the World Wide Web. Don't mistake style for substance. However, while use of the HTML <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 and a wider selection of fonts, so that readers can even better distinguish elements of your document. But most importantly, style sheets let the HTML author 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 style sheet. 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. Internet Explorer 3.0, introduced in the summer of 1996, implements a subset of the W3C standard. Netscape Navigator has broader support for style sheets in Version 4.0, which was introduced in 1997. Style is fast achieving parity with content on the World Wide Web. In keeping with our philosophy of favoring real implementations over standards, we'll start by documenting style sheets as they currently work in the real world. At this writing, style sheets were partially supported by Internet Explorer 3.0 and the third pre-release of Netscape 4.0. We know that browser support of style sheets will change faster than we can reprint this book, so we have created a separate "compliance document" that you can use to determine how style sheets are implemented by the latest releases of the browsers. You can find this document at http://www.ora.com/info/html/. The information in this document should always be considered more timely and accurate than the information in this book. 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. 9.1 The Elements of StylesAt the simplest level, a style is nothing more than a rule that tells the browser how to display a particular HTML tag. Each tag has a number of 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 used to display that tag. Other properties include font attributes, line spacing, margins, borders, and the like, which we describe in detail later in this chapter. 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 types in 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. style attribute Inline Styles: The style AttributeThe 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 to render the contents of just this instance of the tag. For instance, the following style tells the browser to display the level-one 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. Document-Level Style SheetsThe real power of style sheets dawns when you place a list of presentation rules within the head of an HTML 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. 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 content of the <style> tag is not HTML and is not bound by the normal rules for HTML content. The <style> tag, in effect, lets you insert foreign content into your HTML document that the browser uses to format your tags. The <style> tag has just one attribute, type. It defines the types of styles you are including within the tag. Cascading style sheets always carry the type text/css; JavaScript style sheets use the type text/javascript. You may omit the type attribute and hope the browser will figure out the kind of styles you are using. We prefer to include the type attribute so that there is no opportunity for confusion. [the section called "JavaScript Style Sheets"] For example, a style-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:
<head> <title>All True Blue</title> <style type="text/css"> <!-- /* make all H1 headers blue */ H1: {color: blue; font-style: italic} --> </style> </head> <body> <h1>I'm so bluuuuoooo!</h1> ... <h1>I am ba-loooooo, tooooo!<h1> External Style SheetsYou may also place style definitions, like our document-level style sheet example for <h1> tags, in a text file with the MIME type of text/css and import this "external" style sheet into your HTML documents. Because an external style sheet is a file separate from the HTML document 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 importantly, external style sheets give you the power to influence the display styles not only of all related tags in a single documents, 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 our HTML 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 style-conscious browser, and the style isn't overridden by a document-level or inline style definition. You can load external style sheets into your HTML document in two different ways: linked or imported. Linked external style sheetsOne way to load an external style sheet is to use the <link> tag:
<head> <title>Style linked</title> <link rel=stylesheet type="text/css" href="http://www.kumquats.com/styles/gen_styles.css" title="The blues"> </head> <body> <h1>I'm so bluuuuoooo!</h1> ... <h1> I am ba-loooooo, tooooo!<h1> Recall that the <link> tag creates a relationship between the current document and some other document on the Web. In the example, we tell the browser that the document named in the href attribute is a stylesheet, and that its contents conform to the CSS standard, as indicated by the type attribute. We also provide a title for the style sheet, making it available for later reference by the browser. [the section called "The <link> Header Element"] The <link> tag must appear in the <head> of a document. The URL of the style sheet may be absolute or relative to the document's base URL. The type may also be text/javascript, indicating (for Netscape only) that the style rules are written in JavaScript instead of the CSS syntax. [the section called "JavaScript Style Sheets"] Imported external style sheetsThe second technique for loading an external style sheet imports the files with a special command within the <style> tag:
<head> <title>Imported style sheet</title> <style> <!-- @import url(http://www.kumquats.com/styles/gen_styles.css); @import url(http://www.kumquats.com/styles/spec_styles.css); BODY: {background: url(backgrounds/marble.gif)} --> </style> </head> The @import command expects a single URL parameter that names the network path to the external style sheet. The url keyword, parentheses, and trailing semicolon are all required elements of the @import command. The URL may be absolute or relative to the document's base URL. The @import command must appear before any conventional style rules, either in the <style> tag or in an external style sheet. Otherwise, the browser ignores the preceding style definitions. This ordering also means that subsequent style rules can override rules in the imported sheet, and indeed they do. [the section called "URL property values"] The @import command can appear in a document-level style definition or even in another external style sheet, letting you create nested style sheets. Linked Versus Imported Style SheetsAt 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 rules come into play if you include two or more <link> tags within a single document. With one <link> tag, the browser loads the styles in the referenced style sheet and formats the document accordingly, with any document-level and inline styles overriding the external definitions. With two or more <link> tags, the browser presents the user with a list of all the <link>ed style sheets. The user can then select one of the sheets, which is used to format the document. The other <link>ed style sheets are ignored. On the other hand, the style-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 gen_styles.css in our example (9.1.3.2) tells the browser to make <h1> contents blue and italic, and then 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? Imported styles override linked external styles, just as 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 CSS model, the browser will prompt the user to choose between sheet1.css and sheet2.css. It will 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. Limitations of Current BrowsersReferencing a style sheet with the <link> tag currently is the only way to apply an external style sheet to a document. Netscape 4.0 ignores the @import command but continues to process other style rules within the <style> tag. Internet Explorer 3 treats @import as an error. This means that not only does an @imported external style sheet not take effect, but none of the styles following the @import command take effect, either. And, worse, Internet Explorer 3 ignores any and all document-level style rules if you <link> an external one, regardless of whether any of the external rules relate to the same tags or not. Neither Netscape or Internet Explorer support multiple <link>ed style sheets as proposed by the CSS standard. Instead, Netscape loads all the <link>ed style sheets, with rules in later sheets possibly overriding rules in earlier sheets. Internet Explorer only loads the first <link>ed sheet and ignores the remaining sheets. We hope the standard will someday prevail so that style sheets, already mystifying to most, will become that much less confusing. Style CommentsComments are welcome inside the <style> tag and in external style sheets, but don't use a standard HTML comment. Rather, enclose style comments beginning with the sequence /* and ending with */, as we did in the example above. (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. Handling Style-Less BrowsersIn our document-level style examples above, you've probably noticed that we placed the style definition inside an HTML 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, style-conscious browsers ignore HTML comments within a <style> tag. Since style-less browsers will be with us for some time to come, make sure you always place your document-level style rules inside HTML comments. HTML comments should not be used in external style sheets. Style PrecedenceYou 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, in order:
This bug in Internet Explorer will drive authors to distraction. In the following example, Netscape will set the color of the <h1> tag contents green, while Internet Explorer 3 will use red:
<head> <style> <!-- H1 {color: blue; color: red} H1 {color: green} --> </style> Our advice: write styles that conform to the CSS standard. Eventually, Internet Explorer will get fixed, and in the meantime, your documents will look good in Netscape, which is in use by more users anyway. 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 vs. attribute precedence are not clearly elucidated in the W3C CSS standard, nor is there a clear pattern of precedence implemented in the style-conscious browsers. This is particularly unfortunate since there will be an extended period, perhaps several years long, in which users may or may not use a styles-conscious browser. HTML 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. |
|