Bringing CSS and XHTML Together

I’ve mentioned that HTML and XHTML documents have an inherent structure, and that’s a point worth repeating. In fact, that’s part of the problem with web pages of old: too many of us forgot that documents are supposed to have an internal structure, which is altogether different than a visual structure. In our rush to create the coolest-looking pages on the Web, we bent, warped, and generally ignored the idea that pages should contain information that has some structural meaning.

That structure is an inherent part of the relationship between XHTML and CSS; without the structure, there couldn’t be a relationship at all. In order to understand it better, let’s look at an example XHTML document and break it down by pieces:

<html>
<head>
<title>Eric's World of Waffles</title>
<link rel="stylesheet" type="text/css" href="sheet1.css" media="all" />
<style type="text/css">
@import url(sheet2.css);
h1 {color: maroon;}
body {background: yellow;}
/* These are my styles! Yay! */
</style>
</head>
<body>
<h1>Waffles!</h1>
<p style="color: gray;">The most wonderful of all breakfast foods is  
the waffle--a ridged and cratered slab of home-cooked, fluffy goodness 
that makes every child's heart soar with joy. And they're so easy to make!  
Just a simple waffle-maker and some batter, and you're ready for a morning 
of aromatic ecstasy!
</p>
</body>
</html>

The above markup is shown in Figure 1-4.

A simple document

Figure 1-4. A simple document

Now, let’s examine the various ways this document connects to CSS.

The Tag

First, consider the use of the link tag:

<link rel="stylesheet" type="text/css" href="sheet1.css" media="all" />

The link tag is a little-regarded but nonetheless perfectly valid tag that has been hanging around the HTML specification for years just waiting to be put to good use. Its basic purpose is to allow HTML authors to associate other documents with the document containing the link tag. CSS uses it to link style sheets to the document; in Figure 1-5, a style sheet called sheet1.cs s is linked to the document.

A representation of how external style sheets are applied to documents

Figure 1-5. A representation of how external style sheets are applied to documents

These style sheets, which are not part of the HTML document but are still used by it, are referred to as external style sheets. This is because they’re style sheets that are external to the HTML document. (Go figure.)

In order to successfully load an external style sheet, link must be placed inside the head element but may not be placed inside any other element, rather like title. This will cause the web browser to locate and load the style sheet and use whatever styles it contains to render the HTML document in the manner shown in Figure 1-5.

And what is the format of an external style sheet? It’s simply a list of rules, just like those we saw in the previous section and in the example XHTML document, but in this case, the rules are saved into their own file. Just remember that no HTML or any other markup language can be included in the style sheet—only style rules. Here are the contents of an external style sheet:

h1 {color: red;}
h2 {color: maroon; background: white;}
h3 {color: white; background: black;
 font: medium Helvetica;}

That’s all there is to it—no HTML tags or comments at all, just plain-and-simple style declarations. These are saved into a plain-text file and are usually given an extension of .css, as in sheet1.css.

Warning

An external style sheet cannot contain any document markup at all, only CSS rules and comments. The presence of markup in an external style sheet can cause some or all of it to be ignored.

The filename extension is not required, but some browsers won’t recognize the file as containing a style sheet unless it actually ends with .css, even if you do include the correct type of text/css in the link element. In fact, some web servers won’t hand over a file as text/css unless its filename ends with .css. So make sure you name your style sheets appropriately.

Attributes

For the rest of the link tag, the attributes and values are fairly straightforward. rel stands for “relation,” and in this case, the relation is stylesheet. type is always set to text/css. This value describes the type of data that is to be loaded using the link tag. That way, the web browser knows that the style sheet is a CSS style sheet, a fact that will determine how the browser deals with the data it imports. After all, there may be other style languages in the future, such as XSL, so it will be important to declare which language you’re using.

Next, we find the href attribute. The value of this attribute is the URL of your style sheet. This URL can be either absolute or relative, depending on what works for you. In our example, of course, the URL is relative. It could as easily have been something like http://www.meyerweb.com/sheet1.css.

Finally, we have a media attribute. The value that was used, all, means that the style sheet should be applied in all presentation media. There are a number of allowed values for this attribute that are all defined by CSS2:

all

Use in all presentational media.

aural

Use in speech synthesizers, screen readers, and other audio renderings of the document.

braille

Use when rendering the document with a Braille device.

embossed

Use when printing with a Braille printing device.

handheld

Use on handheld devices like personal digital assistants or web-enabled cell phones.

print

Use when printing the document for sighted users and also when displaying a “print preview” of the document.

projection

Use in a projection medium, such as a digital projector used to present a slideshow when delivering a speech.

screen

Use when presenting the document in a screen medium like a desktop computer monitor. All web browsers running on such systems are screen-medium user agents.

tty

Use when delivering the document in a fixed-pitch environment like teletype printers.

tv

Use when the document is being presented on a television.

The majority of these media types are not supported by any current web browser. The three that are the most widely supported are all, screen, and print. As of this writing, Opera also supports projection, which allows a document to be presented as a slideshow.

You can use a style sheet in more than one medium by providing a comma-separated list of the media in which it applies. Thus, for example, you can use a linked style sheet in both screen and projection media:

<link rel="stylesheet" type="text/css" href="visual-sheet.css" 
   media="screen, projection" />

Note that there can be more than one linked style sheet associated with a document. In these cases, only those link tags with a rel of stylesheet will be used in the initial display of the document. Thus, if you wanted to link two style sheets named basic.css and splash.css, it would look like this:

<link rel="stylesheet" type="text/css" href="basic.css" />
<link rel="stylesheet" type="text/css" href="splash.css" />

This will cause the browser to load both style sheets, combine the rules from each, and apply them all to the document. (We’ll see exactly how the sheets are combined in Chapter 3, but for now, let’s just accept that they’re combined.) For example:

<link rel="stylesheet" type="text/css" href="basic.css" />
<link rel="stylesheet" type="text/css" href="splash.css" />

<p class="a1">This paragraph will be gray only if styles from the 
stylesheet 'basic.css' are applied.</p>
<p class="b1">This paragraph will be gray only if styles from the 
stylesheet 'splash.css' are applied.</p>

The one attribute not in your example markup, but could be, is the title attribute. This attribute is not often used, but it could become important in the future and, if used improperly, can have unexpected effects. Why? We will explore that in the next section.

Alternate style sheets

It’s also possible to define alternate style sheets. These are defined by making the value of the rel attribute alternate stylesheet and are used in document presentation only if they are selected by the user.

Should a browser be able to use alternate style sheets, it will use the values of the link elements’ title attributes to generate a list of style alternatives. So you could write the following:

<link rel="stylesheet" type="text/css"
   href="sheet1.css" title="Default" />
<link rel="alternate stylesheet" type="text/css"
   href="bigtext.css" title="Big Text" />
<link rel="alternate stylesheet" type="text/css"
   href="zany.css" title="Crazy colors!" />

Users could then pick the style they want to use, and the browser would switch from the first one (labeled “Default” in this case) to whichever the user picked. Figure 1-6 shows one way in which this selection mechanism is accomplished.

A browser offering alternate style sheet selection

Figure 1-6. A browser offering alternate style sheet selection

Tip

Alternate style sheets are supported in most Gecko-based browsers like Mozilla and Netscape 6+, and in Opera 7. They can be supported in Internet Explorer through the use of JavaScript but are not natively supported by those browsers.

It is also possible to group alternate style sheets together by giving them the same title value. Thus, you make it possible for the user to pick a different presentation for your site in both screen and print media. For example:

<link rel="stylesheet" type="text/css"
   href="sheet1.css" title="Default" media="screen" />
<link rel="stylesheet" type="text/css"
   href="print-sheet1.css" title="Default" media="print" />
<link rel="alternate stylesheet" type="text/css"
   href="bigtext.css" title="Big Text" media="screen" />
<link rel="alternate stylesheet" type="text/css"
   href="print-bigtext.css" title="Big Text" media="print" />

If a user selects “Big Text” from the alternate style sheet selection mechanism in a conforming user agent, then bigtext.css will be used to style the document in the screen medium, and print-bigtext.css will be used in the print medium. Neither sheet1.css nor print-sheet1.css will be used in any medium.

Why is that? Because if you give a link with a rel of stylesheet a title, then you are designating that style sheet as a preferred style sheet. This means that its use is preferred to alternate style sheets, and it will be used when the document is first displayed. Once you select an alternate style sheet, however, the preferred style sheet will not be used.

Furthermore, if you designate a number of style sheets as preferred, then all but one of them will be ignored. Consider:

<link rel="stylesheet" type="text/css"
   href="sheet1.css" title="Default layout" />
<link rel="stylesheet" type="text/css"
   href="sheet2.css" title="Default text sizes" />
<link rel="stylesheet" type="text/css"
   href="sheet3.css" title="Default colors" />

All three link elements now refer to preferred style sheets, thanks to the presence of a title attribute on all three, but only one of them will actually be used in that manner. The other two will be ignored completely. Which two? There’s no way to be certain, as neither HTML nor XHTML provide a method of determining which preferred style sheets should be ignored or which should be used.

If you simply don’t give a stylesheet a title, then it becomes a persistent style sheet and is always used in the display of the document. Often, this is exactly what an author wants.

The style Element

The style element, which is a new element in HTML, is the most common way to define a style sheet, since it appears in the document itself:

<style type="text/css">

style should always use the attribute type; in the case of a CSS document, the correct value is "text/css“, just as it was with the link element.

The style element should always start with <style type="text/css">, as shown in the preceding example. This is followed by one or more styles and is finished with a closing </style> tag. It is also possible to give the style element a media attribute, with the same allowed values as previously discussed for linked style sheets.

The styles between the opening and closing style tags are referred to as the document style sheet or the embedded style sheet since this style sheet is embedded within the document. It will contain many of the styles that will apply to the document, but it can also contain multiple links to external style sheets using the @import directive.

The @import Directive

Now we’ll discuss the stuff that is found inside the style tag. First, we have something very similar to link: the @import directive:

@import url(sheet2.css);

Just like link, @import can be used to direct the web browser to load an external style sheet and use its styles in the rendering of the HTML document. The only major difference is in the actual syntax and placement of the command. As you can see, @import is found inside the style container. It must be placed there, before the other CSS rules, or else it won’t work at all. Consider this example:

<style type="text/css">
@import url(styles.css); /* @import comes first */
h1 {color: gray;}
</style>

Like link, there can be more than one @import statement in a document. Unlike link, however, the style sheets of every @import directive will be loaded and used; there is no way to designate alternate style sheets with @import. So given the following markup:

@import url(sheet2.css);
@import url(blueworld.css);
@import url(zany.css);

all three external style sheets will be loaded, and all of their style rules will be used in the display of this document, as Figure 1-7 illustrates.

Combined styles from @import directives

Figure 1-7. Combined styles from @import directives

Warning

Navigator 4.x and Opera 3.x both ignore @import outright, and several older browsers cannot process varying forms of the @import directive. This can actually be used to one’s advantage in “hiding” styles from these browsers. For more details, see http://w3development.de/css/hide_css_from_browsers/.

As with link, you can restrict imported style sheets to one or more media by listing the media it should be applied to after the style sheet’s URL:

@import url(sheet2.css) all;
@import url(blueworld.css) screen;
@import url(zany.css) projection, print;

@import can be highly useful if you have an external style sheet that needs to use the styles found in other external style sheets. Since external style sheets cannot contain any document markup, the link element can’t be used—but @import can. Therefore, you might have an external style sheet that contains the following:

@import url(http://example.org/library/layout.css);
@import url(basic-text.css);
@import url(printer.css) print;
body {color: red;}
h1 {color: blue;}

Well, maybe not those exact styles, but you get the idea. Note the use of both absolute and relative URLs in the previous example. Either URL form can be used, just as with link.

Note also that the @import directives appear at the beginning of the style sheet, as they did in our example document. It is required by CSS that the @import directive come before any other rules in a style sheet. An @import that comes after other rules (e.g., body {color: red;}) will be ignored by conforming user agents.

Warning

Internet Explorer for Windows does not ignore any @import directive, even those that come after other rules. Since other browsers do ignore improperly placed @import directives, it is easy to mistakenly place the @import directive incorrectly and thus alter the display in other browsers.

Actual Style Rules

After the @import statement in our example, we find some ordinary style rules. What they mean doesn’t actually matter for this discussion, although you can probably guess that they set h1 elements to be maroon and body elements to have a yellow background:

h1 {color: maroon;}
body {background: yellow;}

Styles such as these comprise the bulk of any embedded style sheet—simple and complex, short and long. It will be rare if you have a document where the style element does not contain any rules.

Backward accessibility

For those of you concerned about making your documents accessible to older browsers, there is an important warning to be made. You’re probably aware that browsers ignore tags they don’t recognize; for example, if a web page contains a blooper tag, browsers will completely ignore the tag because it isn’t one they recognize.

The same is true with style sheets. If a browser does not recognize <style> and </style>, it will ignore them altogether. However, the declarations within those tags will not necessarily be ignored because they will appear to be ordinary text so far as the browser is concerned. So your style declarations will appear at the top of your page! (Of course, the browser should ignore the text because it isn’t part of the body element, but this is never the case.)

In order to combat this problem, it is recommended that you enclose your declarations in a comment tag. In the example given here, the beginning of the comment tag appears right after the opening style tag, and the end of the comment appears right before the closing style tag:

<style type="text/css"><!--
@import url(sheet2.css);
h1 {color: maroon;}
body {background: yellow;}
--></style>

This should cause older browsers to completely ignore the declarations as well as the style tags because HTML comments are not displayed. Meanwhile, those browsers that understand CSS will still be able to read the style sheet.

CSS Comments

CSS also allows for comments. These are very similar to C/C++ comments in that they are surrounded by /* and */:

/* This is a CSS1 comment */

Comments can span multiple lines, just as in C++:

/* This is a CSS1 comment, and it
can be several lines long without
any problem whatsoever. */

It’s important to remember that CSS comments cannot be nested. So, for example, this would not be correct:

/* This is a comment, in which we find
 another comment, which is WRONG
   /* Another comment */
 and back to the first comment */

However, it’s hardly ever desirable to nest comments, so this limitation is no big deal.

If you wish to place comments on the same line as markup, then you need to be careful about how you place them. For example, this is the correct way to do it:

h1 {color: gray;}   /* This CSS comment is several lines */
h2 {color: silver;} /* long, but since it is alongside */
p {color: white;}   /* actual styles, each line needs to */
pre {color: gray;}  /* be wrapped in comment markers. */

Given this example, if each line isn’t marked off, then most of the style sheet will become part of the comment and will not work:

h1 {color: gray;}   /* This CSS comment is several lines 
h2 {color: silver;}  long, but since it is not wrapped
p {color: white;}    in comment markers, the last three
pre {color: gray;}   styles are part of the comment. */

In this example, only the first rule (h1 {color: gray;}) will be applied to the document. The rest of the rules, as part of the comment, are ignored by the browser’s rendering engine.

Moving on with the example, you see some more CSS information actually found inside an XHTML tag!

Inline Styles

For cases where you want to simply assign a few styles to one individual element, without the need for embedded or external style sheets, employ the HTML attribute style to set an inline style:

<p style="color: gray;">The most wonderful of all breakfast foods is 
the waffle--a ridged and cratered slab of home-cooked, fluffy goodness...
</p>

The style attribute is new to HTML, and it can be associated with any HTML tag whatsoever, except for those tags that are found outside of body (head or title, for instance).

The syntax of a style attribute is fairly ordinary. In fact, it looks very much like the declarations found in the style container, except here the curly braces are replaced by double quotation marks. So <p style="color: maroon; background: yellow;"> will set the text color to be maroon and the background to be yellow for that paragraph only. No other part of the document will be affected by this declaration.

Note that you can only place a declaration block, not an entire style sheet, inside an inline style attribute. Therefore, you can’t put an @import into a style attribute, nor can you include any complete rules. The only thing you can put into the value of a style attribute is what might go between the curly braces of a rule.

Use of the style attribute is not generally recommended. Indeed, it is marked as deprecated by XHTML 1.1 and is very unlikely to appear in XML languages other than XHTML. Some of the primary advantages of CSS—the ability to organize centralized styles that control an entire document’s appearance or the appearance of all documents on a web server—are negated when you place styles into a style attribute. In many ways, inline styles are not much better than the font tag, although they do have a good deal more flexibility.

Get Cascading Style Sheets: The Definitive Guide, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.