Section III.5. Embedding Style Sheets


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

III.5.1. In-Document Styles

There are two ways to embed the source code for CSS rules directly in an HTML document: using the <style> tag pair or using the style attribute of HTML tags. While placing a style definition in an element's tag flouts the trend toward separating context from rendering, you may encounter valid reasons (explained later) to use this approach from time to time.

III.5.1.1. The <style> tag

The style element is part of the HTML 4 specification (and, by extension, XHTML 1.x specs). The element must be located within the head element and must also include the type attribute. This attribute specifies the content type of the elementtext/css when using the CSS language, as in:

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

Some non-CSS-aware browsers (an extreme rarity, these days) 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, 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.

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 elementthe HTML tag stripped of its enclosing angle brackets (e.g., the p selector, which represents all paragraph elements 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 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 (as in the type of element).

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 property 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 (or rule) 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 element, nor is there a limit to the number of style properties that can be defined in a style rule. Also, rule sets can appear in any order within a style sheet (although order may play a significant role, as described later), and the indenting shown in the preceding example is purely optional. White space (spaces or line breaks) between property/value pairs and before or after curly braces is not critical. As a result you can also break up a series of declarations (inside the curly braces) so that each property/value pair appears on its own line, as follows:

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

This format, popular with CSS designers, makes it easier to locate a rule for a particular selector and also spot which rules in a complex style sheet contain a particular CSS property name.

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

III.5.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 property/value pairs in the default CSS style sheet syntax. These style property/value pairs use the colon assignment operator. Use a semicolon to separate multiple style property settings within the same style attribute. The following code uses a style attribute version of the example shown in the preceding section. Because the style sheet rules 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.

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

III.5.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 importing technique, 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).

III.5.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 1 of Dynamic HTML, Third Edition).

The CSS2 specification stakes its claim to the link element as a way to load 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> 

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

III.5.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 4 of Dynamic HTML, Third Edition.)

One such at-rule that is implemented starting in IE 4 and is now supported by all mainstream browsers 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.

III.5.3. Loading Browser-Specific Style Sheets

Due to fluctuations in interpretations of CSS from one browser to another, you may be faced with an occasional need to import different style sheets for different browsers or browser generations. Among the biggest problems you'll encounter are radical departures from the CSS box model in Internet Explorer for Windows prior to IE 6 (and IE 6 or later running in "quirks mode").

Scripters tend to look first at a scripted solution, incorporating "browser sniffing" to determine the current browser through the navigator.userAgent property value. A branching script can then insert a link element that loads the desired .css file. Unfortunately, the proliferation of values for the userAgent property make such scripts hazardous for future compatibilityunless you are trying to isolate a very specific, older browser version that requires special consideration.

Starting with IE 5, Microsoft built in a separate branching mechanism called conditional comments. Coding consists of short conditional expressions inside HTML comments. If the current browser meets the condition, then HTML between the comment tags is rendered; otherwise (and this goes for non-IE browsers), the HTML code inside the comments is ignored. For example, if you wish to load a special style sheet for IE 5 and 5.5, you can do so and have it override the one that all other browsers use, as follows:

 <link rel="stylesheet" type="text/css" href="basestyle.css"> <!--[if lt IE6]>        <link rel="stylesheet" type="text/css" href="badboxstyle.css"> <![end if]--> 

For the full syntax of conditional comments, see the <!--comment--> element at the end of Chapter 1 of Dynamic HTML, Third Edition.

III.5.4. Selecting a Style Sheet Style

In deciding among the many ways to introduce style sheets into your pagesthe <style> tag, the style attribute, or imported from outside the documentyou need to consider how important it is for you to separate design from content. Within a single document file, 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 or web site, such a change requires much more effort and the possibility for mistakes increases.

As discussed in Online Section V, 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 of styles applied through <style> or imported style sheet rules requires special syntax that is incompatible between IE and W3C DOM implementations, as discussed in Online Section V.

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.




Dynamic HTML. The Definitive Reference
Dynamic HTML: The Definitive Reference
ISBN: 0596527403
EAN: 2147483647
Year: 2004
Pages: 120
Authors: Danny Goodman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net