home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


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.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.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.