Hypermedia Production, Fall 1998
Style Sheets Handout 1

1. What are Style Sheets?

The first Cascading Style Sheets specification (CSS1) was put forward by the World Wide Web Consortium as a major augmentation of Hypertext Markup Language and a key element of HTML 4.0. Along with the Document Object Model (to which we're coming in a few weeks), it forms the backbone of Dynamic HTML. Most recent browsers (Netscape Navigator and Microsoft Internet Explorer 4-series) implement about 85% of the CSS1 spec. Full implementation is promised in the next release (5.0) of both browsers. Netscape has proposed a competing specification called JavaScript Accessible Style Sheets (JASS), but it has not received much support (and as you'll see in the coming weeks, CSS Style Sheets are also accessible to JavaScript).

If you've ever used templates, pre-defined formats, or styles in a word processor, then you know what style sheets do: they allow you to predefine a range of features, such as font size and family, character and background color, margin width, leading, etc., and to group these definitions into units that can be applied flexibly to various parts of your document. The benefits of this tool are basically two:

  • To further separate document structure from document production or appearance;

  • To give authors greater control over elements of appearance, including greatly improved management of typography, absolute positioning of page elements, and layering in three dimensions.

2. How do Style Sheets work?

Style Sheets have a certain similarity to JavaScript, though they're not strictly speaking related: both are control structures added to "vanilla" HTML either through linked, "external" documents or by inclusion in the markup within special containers. We'll cover three basic methods for using style sheets, though there are really more options than these:

  • Definition of a page-specific or internal style sheet in the <HEAD> portion of the markup;

  • Inclusion of <STYLE> containers as in-line elements within the content or <BODY> portion of the markup;

  • Linking to external CSS files (external style sheets).

3. Internal Style Sheets

Here's a simple example of a page-specific or internal style sheet:

    <style type="text/css"> <!-- body { width: 450 } --> </style>

A few basics before we get into the heart of the matter. Note that the <STYLE> container has a type attribute. This is required, at least for Netscape-4 browsers. Also notice the comment tags <!-- and --> bracketing all the material within the <STYLE> container. Browsers earlier than Netscape 4.0 and MSIE 3.0 can't understand style sheets and will actually display the style sheet instructions unless those instructions are "commented out." (This used to be necessary for JavaScript, too, but most browsers today can at least recognize JavaScript.)

You may omit the comment tags (sometimes called "cloaking tags") if you include a test for appropriate browser types in your page. For the sake of clarity I will leave them out of subsequent code examples. If you do cloak your style sheet code, be careful to put the comment tags inside the <STYLE> container. If you put them outside that container, your entire style sheet will be ignored even by browsers that support style sheets.

Now to the main business of the style sheet. Within the <STYLE> container in this example we find a single element called a rule. All style sheet rules follow this general format (though line breaks and indenting are optional):

    selector { declaration }

In our example the word body is the selector of the rule. It indicates a tag or container within the page markup to which the rule applies; in this case the <BODY> container. Within the { curly braces } comes the declaration part of the rule, which specifies the particular treatment we want for the <BODY> container. In this case we set the width property of <BODY> to 450 pixels. Note the form of the declaration, which is simply the name of the property followed by a colon, a space, and the value for that property.

The rule in our example restricts all elements within the body of the page to a right margin at 450 pixels. It has the same effect as using a layout table with width set to 450; though of course the table requires six tags -- <TABLE><TR><TD> </TD></TR></TABLE> -- instead of the single line in the style sheet. (Is this the end of layout tables? Maybe not until everyone has a CSS-capable browser; but the day is coming.)

Rule declarations may affect more than one property of the target tag or container. In such cases the multiple elements of the declaration are separated by semicolons. For example:

    <style type="text/css"> body { width: 450; font: 10 pt Courier; } </style>

This style sheet sets page width to 450 pixels and sets the default font to Courier at 10 points. Style sheets let you finally specify exact font sizes in pixels or picas, and even better, this specification overrides any user settings!

4. In-line Style Sheets

The style sheets we've just seen are meant to apply to a single page, but style sheets are in fact much more flexible. Style sheet rules can be incorporated into specific tags to make local changes within the flow of the page. Here's how it's done:

    <P style="color: 009900">Color me green, please.</P>

As you can see, the key to in-line styling is the style attribute, which can be inserted into a variety of tags. (Which tags? It depends on your browser; see Mulder for the current rundown. When in doubt, experiment.) You do not need to "cloak" in-line style attributes with comments (and how would you, anyway?); browsers that don't understand style sheets simply ignore the style attribute.

The argument of the style attribute goes inside double quotes just like all arguments. It looks exactly the same as it would in any other style sheet, except we put all elements of the rule in a single line. A more complex in-line rule might look like this:

    <P style="color: 009900; font: 18pt Helvetica">Yikes!</P>

Here we've been styling the <P> or paragraph tag. Note that for style sheet purposes, <P> is a container; that is, it requires a closing </P> tag. If you've been writing HTML for a while now, you may be using just a single <P> tag to insert line skips. Change that practice now. Always use </P> at the end of paragraphs. In most cases, style sheets will malfunction if you don't; plus it's just good markup style to close the paragraph container.

You may be wondering about the usefulness of in-line style sheets. After all, we can set some of the properties above using a <FONT> container, thus:

    <P><FONT family="helvetica" color="009900" size="4">Yikes! </FONT></P>

But note that setting font size to 4 is not the same as setting font to 18 points. Font size 4 is a relative measure dependent on user settings. It's unlikely to work out to 18 points. Style sheets generally allow more precise control of page elements; they also give you command of some features not included in standard HTML (e.g., page width as in our previous examples).

Why put the styling in the tag as opposed to the top of the page, though? Again, the best reason is precision. In-line style "sheets" (actually style attributes) apply only to a specific tag or container. Even better, they locally override any general rule set by a higher-level style sheet. That's right -- you can use as many style sheets in a given Web page as your twisted mind desires. They don't call 'em "cascading" style sheets for nothing: control flows gracefully down the document hierarchy from general to particular. You can define a general style for <P> containers (say, a default font setting of blue, 14 point Times) then re-style one paragraph in red, 26 point Helvetica for special emphasis. The next paragraph following the one with the in-line styling will revert to the default settings.

5. External Style Sheets

As we learned last week, it's possible to link a page to JavaScript instructions that reside in a separate file, giving us the capability to define elements on many pages with instructions we only need to write and maintain in a single place. Style sheets also offer this facility. Similar to external JavaScript files, external style sheets are simple text (ASCII) files with the extension .css. They contain style sheet material without a <STYLE> container (just as external .js pages have no <SCRIPT> container). To link to an external style sheet, I insert a <LINK> tag in the HEAD portion of the markup:

    <LINK REL="stylesheet" HREF="myStyle.css" TYPE="text/css">

As in the case of JavaScript, the HREF attribute may be fully qualified, containing an entire Internet address, or may contain a relative path within the local file structure. This means, of course, that you can link your pages to style sheets maintained on servers anywhere in the world.

External style sheets enter the cascade along with everything else. In most cases they rank above in-line and internal style sheets in level of generality, meaning that you can use either of the other two kinds of styling to locally override rules made in an external file. There may be some exceptions owing to bad implementation of CSS1 by both Netscape and Microsoft. These are spelled out in Mulder's book, and they're pretty obscure.

6. DIVs and SPANs

When working with style sheets you will sometimes need to style parts of the page that don't correspond to familiar HTML elements. For example, suppose we want to set the second sentence of a paragraph in red letters against a bright yellow background, and we want to do this without breaking the flow of the paragraph. We can't style the <P> container because it would affect all the sentences in the paragraph, and we can't insert another <P> container because that would force a paragraph break.

To solve this problem, we may use either of two formerly obsure containers: <DIV> or <SPAN>. Both simply mark off a section of a Web page without respect to other structures such as paragraph breaks or lists. Either container can be placed around one sentence of a paragraph, or indeed around a passage that begins in one paragraph and runs over into the next, or around the entire <BODY> section of the page if you like. You may use <DIV> and <SPAN> interchangeably, though technically speaking <DIV> (short for "division") should be used for larger domains of the document than <SPAN>, which some people reserve for words, phrases, and other elements smaller than a sentence. These two containers will be especially useful when we start manipulating elements with DHTML in a few weeks.

7. Classes

As we've seen, in-line style attributes let us change the appearance of particular tags locally. But suppose we want to make the same local change several times in our document? For instance, on a page with 35 paragraphs (okay, it's a long page), paragraphs 3, 8, 17, 29, 31, 32, and 35 must appear in bold blue type against a pale yellow background. We could enter style attributes in the initial <P> tag for each of those six paragraphs; but there's an easier way.

Using an internal style sheet (within the HEAD section of the page) or an external stylesheet in an separate file, we may define a special class of <P> that would be styled precisely as we want it. The rule might look like this:

    P.ROQUEFORT { background: FFFFCC; color: 0000CC; }

The designation ".ROQUEFORT" indicates the class that is being style here. You may use any word to designate a class -- though it's never a good idea to use words also used in HTML such as "head," "body," etc. We would probably have another rule, either before or after this one, styling the <P> tag in general. To determine which paragraphs follow this rule, we simply add an attribute to the initial tag:

    <P class="ROQUEFORT"> ... </P>

8. A Note About Fonts

You can specify fonts by name (and as you'll see in Mulder, in several more interesting ways as well), but what happens if the font you've named is not installed in the user's operating system? Generally speaking, the browser looks for alternatives. If it finds none, it just uses the default, which is usually some version of Times. You can structure your font style so that it includes a series of fonts, for instance:

    P { font-family: Caslon, Bookman, serif }

Here the browser would look for both the Caslon and Bookman fonts. In this case we've thrown in a last-ditch option, serif, which indicates not a particular font but a general category of font -- anything with little flourishes on the letter forms. Mulder says that all Mac browsers from MSIE 3.0 and Navigator 4.0 will support this trick, though apparently no Windows browsers will. (What do Windows users know about fonts, anwyay?)

If you want your font choices to work across the widest possible variety of platforms, you're stuck with Times and Courier. Helvetica (Mac) and Arial (Windows) are nearly identical, but you must include both font names in your rule to be sure they will substitute correctly. Microsoft Internet Explorer installs several fonts into the user's system, so if you're building for that browser exclusively, you may add Arial Black, Comic Sans MS, Impact, and Verdana. This is true for both Mac and Windows.

Note that there are plans by both Netscape and Microsoft to deploy downloadable fonts. These fonts would stream in across the Internet and install themselves temporarily in the user's system. At the moment, Netscape and Microsoft are each pushing incompatible versions of this technology; and of course, it could represent an enormous security risk. So don't hold your breath. For more coverage of font matters, see Mulder's Appendix B.