Dynamic HTML: The Definitive Reference, 2rd Ed.Dynamic HTML: The Definitive ReferenceSearch this book

3.6. Embedding Style Sheets

You add style sheets to a document by defining them explicitly in the document's source code, importing definitions from one or more external files, or a combination of the two. In-document and external style sheets coexist well in the same document; you can have as many of each type as your page design requires.

3.6.1. In-Document Styles

There are two ways to embed CSS information directly in an HTML document: using the <style> tag pair or using style attributes of HTML tags. For ease of maintenance and consistency throughout a document, I recommend using a <style> tag inside the head section of the document. While placing a style definition in an element's tag flaunts the trend toward separating context from rendering, you may encounter valid reasons (explained later) to use this approach from time to time.

3.6.1.1. The <style> tag

It is convenient to define style sheet rules between <style> and </style> tags. Because the body element is the container of the rendered content, you should use the <style> tag in the head section of your document. This placement also guarantees that the style sheet is loaded and in effect before any elements of the document are rendered. Include the type attribute in the opening tag, as in:

<style type="text/css">
    style sheet rule(s) here
</style>

Some pre-CSS browsers ignore the start and end tags and attempt to render the rules as if they were part of the document body. If you fear that this will affect users of your pages, you can surround the statements inside the style element with HTML comment symbols. Such a framework looks as follows:

<style type="text/css">
<!--
    style sheet rule(s) here
-->
</style>

This technique is similar to the one used to hide the contents of <script> tag pairs from older browsers, except that the end-comment statement in a script must start with a JavaScript comment symbol (//-->). The comment-bracketed content is still downloaded to the client and is visible in the source code, but for all but the most brain-dead browsers, the style sheet rules are hidden from plain view in the browser window. In the examples in this book, I have omitted these comment symbols to conserve space and improve readability, but it's a good idea to use them for public web pages.

As I mentioned earlier, the link between a style declaration and the element(s) it governs is called a selector. In practice, "selector" has a wide range of meanings. In its simplest form, a selector is the name of one type of HTML element—the HTML tag stripped of its enclosing angle brackets (e.g., the p selector, which represents all the paragraphs in a document). As you will see as this chapter progresses, a selector can take on additional forms, including some that have no resemblance at all to HTML elements. Just remember that a selector defines the part (or parts) of an HTML document that is governed by a style declaration.

In the most common application, each style rule binds a declaration to a particular type of HTML element based on the element's tag name. Get in the habit of using lowercase tag selectors to match the XHTML-inspired lowercase tag names. This simplest selector form is called a type selector. When a rule is specified in a <style> tag, the declaration portion of the rule must appear inside curly braces, even if there is just one style attribute in the declaration. Each curly brace pair and its content is known as a declaration block. The combination of a selector and a declaration block comprises a rule set. The style sheet in the following example includes two rule sets. The first assigns the red foreground (text) color and initial capital text transform to all h1 elements in the document; the second assigns the blue text color to all p elements:

<html>
<head>
<style type="text/css">
    h1 {color:red; text-transform:capitalize}
    p {color:blue}
</style>
</head>
<body>
<h1>Some heading</h1>
<p>Some paragraph text.</p>
</body>
</html>

There is no practical limit to the number of rule sets that can be listed inside the <style> tag pair, nor is there a limit to the number of style attributes that can be used in a style rule. Also, rule sets can appear in any order within a style sheet, and the indenting shown in the preceding example is purely optional. White space between attribute/value pairs is not critical; as a result you can also break up a series of declarations (inside the curly braces) so that each attribute/value pair appears on its own line, as follows:

h1 {
       color:red;
       text-transform:capitalize;
   }

CSS syntax provides a shortcut for assigning the same style declaration to more than one selector. By preceding the curly-braced style declaration block with a comma-delimited list of selectors, you can have one statement do the work of two or more statements. For example, if you want to assign the same color to h1, h2, and h3 elements in the document, you can do so with one statement:

<style type="text/css">
    h1, h2, h3 {color:blue}
</style>

This selector grouping technique is applicable to all CSS selector types described in this chapter.

3.6.1.2. The style attribute in element tags

Another way to bind a style declaration to an HTML element is to include the declaration as an attribute of the actual HTML element tag. The declaration is assigned to the style attribute; almost every HTML element recognizes the style attribute.

Because the style attribute is a regular HTML attribute, you assign a value to it via the equal sign operator. The value is a double-quoted string that consists of one or more style attribute/value pairs in the default CSS style sheet syntax. These style attribute/value pairs use the colon assignment operator. Use a semicolon to separate multiple style attribute settings within the same style attribute. The following code uses a style attribute version of the <style> tag example shown in the preceding section. Because the style sheets are attached to the actual HTML element tags, all this takes place in the body section of the document:

<body>
<h1 style="color:red; text-transform:capitalize">Some heading</h1>
<p style="color:blue">Some paragraph text.</p>
</body>

Notice, too, that when a style sheet definition is specified as a style attribute, there are no curly braces involved. The double quotes surrounding the entire style sheet definition function as the curly brace grouping characters.

3.6.2. Importing External Style Sheets

Perhaps the most common use of style sheets in the publishing world is to establish a "look" designed to pervade across all documents, or at least across all sections of a large document. To facilitate applying a style sheet across multiple HTML pages, the CSS specification provides two ways to include external style sheet files: an implementation of the <link> tag and a special type of style sheet rule selector called the @import rule.

3.6.2.1. External style sheet files

No matter how you import an external style sheet, the external file must be written in such a way that the browser can use it to build the library of style sheets that controls the currently loaded document. In other words, the browser must take into account not only external styles, but any other styles that might also be defined inside the document. Because there is an opportunity for the overlap of multiple style sheets in a document, the browser must see how all the styles are bound to elements, so it can apply cascading rules (described later in this chapter) to render the content.

An external style sheet file consists exclusively of style sheet rule sets without any HTML tags. The file should be in plain text format and saved with the .css filename extension. For example, to convert the style sheet used in the previous sections to an external style sheet file, create a text file that contains the following and save the file as basestyle.css:

h1 {color:red; text-transform:capitalize}
p {color:blue}

When a browser encounters either technique for importing an external style sheet, the content of the file is loaded into the browser as if it were typed into the main HTML document at that source code location (although it doesn't become part of the source code if you use the browser to view the source). The web server must also be configured to associate the .css filename extension with a content-type of text/css (most modern servers are already set up this way, but check with the server administrator if you're not sure).

3.6.2.2. The link element

HTML recognizes <link> as a general-purpose tag for linking media-independent content into a document (not to be confused with hypertext links created by the <a> tag). It is up to the browser to know how to work with the various attributes of this tag (see Chapter 8).

The CSS2 specification claims one application of the link element as a way to link an external style sheet file into a document. The attributes and format for the tag are rather simple:

<link rel="stylesheet"  type="contentType" href="filename.css">

The contentType value for CSS style sheets is text/css. If the style sheet in the previous section is saved as basestyle.css, you can import that style sheet as follows:

<html>
<head>
<link rel="stylesheet" type="text/css" href="basestyle.css">
</head>
<body>
<h1>Some heading</h1>
<p>Some paragraph text.</p>
</body>
</html>

A document can have multiple link elements for importing multiple external style sheet files (only one file per link element). The document can also contain style elements as well as style attributes embedded within element tags. But if there is any overlap of more than one style applying to the same element, the cascade rules (described later in this chapter) determine the specific style sheet rule that governs the element's display.

3.6.2.3. The @import rule

CSS2 describes an extensible system for declarations or directives (commands, if you will) that become a part of a style sheet definition. They are called at-rules because a rule starts with the "at" symbol (@), followed by an identifier for the declaration. Each at-rule includes one or more descriptors that define the characteristics of the rule and end with a semicolon. (For more about at-rules, see Chapter 11.)

One such at-rule that is implemented starting in IE 4 and Netscape 6 imports an external style sheet file from inside a style element. It performs the same function as the link import technique described in the previous section. In the following example, a file containing style sheet rules is imported into the current document:

<style type="text/css">
    @import url("styles/corporate.css");
</style>

You may include multiple @import rules in a style element, but they must come before rules with any other type of selector. An @import rule must also stand alone, without being nested inside curly brace blocks.

If you are creating documents for browser versions that support the @import rule, it's easier to find style references by keeping all style sheet definitions within the style element rather than spreading the import job to a separate link element.

3.6.3. Selecting a Style Sheet Style

In deciding among the many ways to introduce style sheets into your pages—the <style> tag, the style attribute, or imported from outside the document—you need to consider how important it is for you to separate design from content. The <style> tag technique distances HTML content from the styles associated with elements throughout the document. If you need to change a font family or size for a particular kind of element, you can do so quickly and reliably by making the change to one location in the document. If, on the other hand, your style definitions are scattered among dozens or hundreds of tags throughout the document, such a change requires much more effort and the possibility for mistakes increases. However, for small-scale deployment of style sheets, the style attribute will certainly do the job. And, if one person is responsible for both content and design, it isn't too difficult to keep the content and design in sync.

As discussed in Chapter 4, where you declare an element's style impacts how DHTML scripts read the element's initial style properties. An element object's style property reflects only values assigned via the element tag's style attribute. In contrast, reading the initial value styles applied through <style> or imported style sheet rules requires special syntax that is incompatible between IE and W3C DOM implementations, as discussed in Chapter 4.

Current web development trends lean toward the separation of design from content. In large projects involving writers, designers, and programmers, it is usually easier to manage the entire project if different contributors to the application can work toward the same goal without stepping on each other's code along the way. It is no accident that both style sheets and scripts have acquired mechanisms for importing external files into an HTML document. This allows designers to work on their .css files and programmers to work on their .js files, all of which blend into the writer's .html file (or equivalent server output) that arrives at the client.



Library Navigation Links

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