8.1 The Elements of StylesAt the simplest level, a style is nothing more than a rule that tells the browser how to render a particular HTML or XHTML tag's contents.[2] 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 in which Netscape or Internet Explorer should 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.
There are three ways to attach a style to a tag: inline, on the document level, or through the use of an external style sheet. 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 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 and values to render the contents of that 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, but also colored blue and italicized: <h1 style="color: blue; font-style: italic">I'm so bluuuuoooo!</h1> Inline styles can be difficult to maintain, because they add more contents to their tags' definitions, making them harder to read. Also, because they have only a local effect, they must be sprinkled throughout your document. Use the inline style attribute sparingly and only in those rare circumstances when you cannot achieve the same effects otherwise. 8.1.2 Document-Level Style SheetsThe real power of style sheets becomes more evident when you place a list of presentation rules at the beginning of your HTML or XHTML document. Placed within the <head> and enclosed within their own <style> and </style> tags, document-level style sheets affect all the same tags within that document, except for tags that contain overriding inline style attributes.[3]
Everything between the <style> and </style> tags is considered part of the style rules that the browser is to apply when rendering the document. Actually, 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 displays the contents of all <h1> tags as blue, italic text in an HTML 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 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.2.1 The type attributeThere are other types of style sheets available for HTML/XHTML besides CSS. Like the JavaScript style sheets we describe in Chapter 12, they are not well supported, if at all, by the popular browsers, so we don't spend a lot of time on them in this book. Nonetheless, the browser needs a way to distinguish which style sheet you use in your document. Use the type attribute within the <style> tag for that. Cascading style sheets are all type text/css; JavaScript style sheets use the type text/javascript. You may omit the type attribute and hope the browser figures out the kind of styles you are using, but we suggest you always include the type attribute, so there is no opportunity for confusion. [Section 12.4] 8.1.2.2 The media attributeHTML and XHTML documents can wind up in the strangest places these days, such as on cellular phones. To help the browser figure out the best way to render your documents, include the media attribute within the <style> tag. The value of this attribute is the document's intended medium, although it doesn't preclude rendering by other media. The default value is screen (computer display). Other values include tty (text only), tv (television), projection (theaters), handheld (PDAs and cell phones), print (ink on paper), braille (tactile devices), embossed (Braille printers), aural (audio; speech synthesis, for instance), and all (many different types of media). If you want to explicitly list several types of media, rather than specifying all, use a quote-enclosed, comma-separated list of media types as the value of the media attribute. For example: <style type="text/css" media="screen,print"> tells the browser that your document contains CSS both for printing and for computer displays. Take caution when specifying media, because the browser cannot apply the styles you define unless the document is being rendered on one of your specified media. Thus, the browser would not apply our example set of styles designed for media="screen,print" if the user is, for instance, connected to the Web with a handheld computer. How do you create different style definitions for different media without creating multiple copies of your document? The CSS2 standard lets you define media-specific style sheets through its extension to the @import at-rule and through the @media at-rule, which we describe in Section 8.1.4. 8.1.2.3 The dir, lang, and title attributesAs with any HTML/XHTML element, you can associate a descriptive title with the <style> tag. If the browser displays this title to the user, it uses the values of the dir and lang attributes to render it correctly. [Section 3.6.1.1] [Section 3.6.1.2] [Section 4.1.1.4] 8.1.3 External Style SheetsYou can also place style definitions into a separate document (a text file with the MIME type of text/css) and import this "external" style sheet into your document. The same style sheet can actually be used for multiple 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 importantly, external style sheets give you the power to influence the display styles of all related tags not only in a single document but in an entire collection of documents. For example, suppose we create a file named gen_styles.css containing the following 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 colors all the <h1> tag contents blue and renders the text in italic. Of course, that is true only if the user's machine is capable of these style tricks, she's using a styles-conscious browser such as 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: linking them or importing them. 8.1.3.1 Linked external style sheetsOne way to load an external style sheet is to use the <link> tag within the <head> of your document: <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 this example, we tell the browser that the document named in the href attribute is a cascading style sheet (css), as indicated by the type attribute. These two attributes are required. We also explicitly tell the browser that the file's relationship to our document is that it is a stylesheet and we provide a title making it available for later reference by the browser. [Section 6.7.2] The style sheet-specifying <link> tag and its required href and type attributes 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. 8.1.3.2 Imported external style sheetsThe second technique for loading an external style sheet imports the file with a special command (a.k.a. at-rule) within the <style> tag: <head> <title>Imported style sheet</title> <style type="text/css"> <!-- @import url(http://www.kumquats.com/styles/gen_styles.css); @import "http://www.kumquats.com/styles/spec_styles.css"; body {background: url(backgrounds/marble.gif)} --> </style> </head> The @import at-rule expects a single URL for the network path to the external style sheet. As shown in this example, the URL may be either a string enclosed in double quotes and ending with a semicolon or the contents of the url keyword, enclosed in parentheses, with a trailing semicolon. The URL may be absolute or relative to the document's base URL. The @import at-rule must appear before any conventional style rules, either in the <style> tag or in an external style sheet. Otherwise, the standard insists that the browser ignore the errant @import. By first importing all the various style sheets, then processing document-level style rules, the CSS2 standard cascades: the last one standing wins. [Section 8.4.1.4] The @import at-rule can appear in a document-level style definition or even in another external style sheet, letting you create nested style sheets. 8.1.4 Media-Specific StylesBesides 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 renders 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 that access 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 loads and uses an imported style sheet. 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 whether 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 @import CSS2 media types are the same as those for the <style> tag's media attribute, including all, aural, braille, embossed, handheld, print, projection, screen, tty, 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 contents of the <style> tag. The at-rules may not appear within another rule. Unlike @import, @media may appear subsequent to other style rules, and its style-rule contents 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 brace ({})-enclosed set of style rules. For example: body {background: white} @media tv, projection { body {background: lt_blue} } The lt_blue attribute to the @media at-rule causes the body's background color to display light blue, rather than the default white set in the general style rule, when the document is rendered on a television or projection screen (as specified by the tv and projection attributes). 8.1.5 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 CSS2-standard rules come into play if you include two or more <link> tags within a single document. 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 linked style sheets. The user then selects one of the linked sheets, which the browser loads and uses to format the document; the other linked 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 first tells the browser to make <h1> contents blue and italic, and then a later spec_styles.css tells the browser to make <h1> text red, then the <h1> tag contents 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 are all 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, 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 BrowsersInternet Explorer and Netscape support the <link> tag to apply an external style sheet to a document. Neither Netscape nor Internet Explorer supports multiple, user-selectable <link> style sheets, as proposed by the CSS2 standard. Instead, they treat the <link> style sheets as they do @import or document-level styles, by cascading the rules. Netscape Version 6, but not earlier versions, and Internet Explorer Versions 5 and later honor 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 earlier Netscape browsers is hopeless. Assume, therefore, that most people who have Netscape Version 4 will render your documents on a common PC screen, so make that medium the default. 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 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. 8.1.7 Style CommentsComments 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 between /* and */ markers, as we did in the example in Section 8.1.2. (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 cannot 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 Styleless BrowsersWe have to do some fancy footwork to allow our HTML documents to work with both older, styleless browsers and newer, styles-conscious browsers. The order of the tags is very important. Here's the approach, which you may have noticed in our document-level style examples: <style> <!-- @import url(sheet3.css); @import url(sheet4.css); --> </style> First, we use a <style> tag, followed by an HTML comment, followed by our style rules. We close the comment, and we close the </style> tag. Newer browsers ignore HTML comments within <style> tags, so these browsers implement our styles correctly. Older browsers ignore what is placed between HTML comments, so they ignore our style rules (which they would otherwise print on the screen, to the confusion of the user). XHTML documents require a slightly different approach. In those documents, we enclose document-level styles in a CDATA section instead of in HTML comments. See Section 16.3.7 for details. In the style sheets themselves, use style comments rather than HTML comments. The styleless browsers won't load the style sheets, and newer browsers interpret them correctly. 8.1.9 Style PrecedenceYou may import multiple external style sheets 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 that 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:
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 elucidated in the W3C CSS2 standard, but no clear pattern of precedence is implemented in the styles-conscious browsers. This is particularly unfortunate because there will be an extended period, perhaps several years, in which users may or may not use styles-conscious browsers. Authors must 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 such as 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. |