Creating Cool HTML 4 Web Pages

Chapter 14: Style Sheets

Introduction | Inline style information | Header styles | External style sheets | Cool tricks

If there's one thing that's constant with the Web, it's change. The HTML language itself is no different, as you have learned, but the one change that's formalized in the 4.0 specification of the hypertext markup language that has the potential to totally change the Web is style sheets. Known more formally as Cascading Style Sheets (CSS), it's a way for us Web designers to redefine the meaning of any HTML tag within a document or throughout a site.

That's the good news. The bad news is that the way you work with style sheet information is awkward and a bit cryptic because it's been retrofitted into the existing HTML language. Nonetheless, if I have to point to one change in HTML 4.0 that's most significant, it's unquestionably the addition of cascading style sheets.

It's interesting to note that the different releases of the major Web browsers on the Mac and PC have varying levels of support for the attributes you can set within style sheets. In particular, while Netscape Navigator 4.0 for Windows 95 has a considerable amount of support for style sheets, the same release for the Macintosh only supports a small subset of style sheets. Microsoft's Internet Explorer has supported the additional style sheet capabilities since its 3.0 release. Even with the support in the latest versions, there are still elements in the style specification that aren't supported at all yet.

And that brings up the biggest dilemma for designers who want to leap headlong into using style sheets: If it's not even fully supported in the very latest version of the most popular browser on the Net, what percentage of people who come to your CSS-dependent Web site will be able to see what you've designed? In the marketing biz, people often refer to a bell-shaped curve of technology adopters, talking about the "early adopters" as those who jump onto a bandwagon because it's new and different. But these early adopters are always a small subset of the overall market (how many of your friends have a DVD player or digital cellular phone today?). That's exactly the same problem with style sheets as I write this chapter: Are my Web pages targeted to a small subset of the online community, or am I seeking to appeal to the majority of online people within a specific interest group?

For your projects, it's a question only you can answer. Some sites you design might be ultimately for yourself, as a learning experience, and so using the best, coolest, state of the art formatting tags and style sheet information is perfect. Other sites that you're developing for a paying client whose mom has a WebTV unit, well, you'll want to be more careful about relying on the style sheet information on the page to get the effect you seek.

There is a middle ground. As we'll see in a bit, you can definitely add style sheet information to your page but have the page gracefully degrade and still be attractive in earlier browsers. Indeed, this concept of "graceful degradation" is critical to successful Web page design. It's okay in my book (which this is!) to use the newest tags if the page still looks acceptable with older browsers or less high-tech equipment.

Okay, enough warnings. Let's jump in headfirst and look at the style sheet specifics and how to use them to have a far greater level of control over the appearance of your pages and overall site.

Introduction to Style Sheets

Even with all the comments above, I really want to emphasize here that of the changes that the 4.0 spec have brought to the Web developer community, none will be more pervasive and important, eventually, than style sheets. It's a big step away from the original paradigm of the Web, where you have "suggestions" for formatting like <STRONG> and <H1>, and the browser (as configured by the user) would decide exactly how it should appear on the screen. Instead, style sheets will let you, the Web page designer, define the exact size of typeface to use, the color, the typeface itself, and lots more for any given HTML tag.


Note Read the entire CSS specification for yourself, if you're so inclined, by popping over to http://www.w3.org/TR/REC-CSS1-961217.html. Even better, WebReview has a terrific online table that shows you what specific style attributes are supported by which versions of the major browsers. You can see it for yourself at http://style.webreview.com/mastergrid.html

All of this magic is buried in HTML comments that are themselves buried in the <STYLE> tag. Why buried in comments? So browsers that don't understand styles won't get confused -- just like how JavaScript and VBScript are included in Web documents. Let's start by looking at a simple Web page using existing HTML tags to accomplish some indentation and typeface changes:

Here's a regular paragraph of information.
<P>
<FONT FACE=courier>
This is some code to show, it should be in 'courier' and 
it should have lots of space between the lines of text, 
more than would normally be the case with a medium-size 
typeface.
</FONT>
<BLOCKQUOTE>
<FONT SIZE=+1 FACE="helvetica" COLOR=red>
And don't forget this important - indented - note too! 
But look, it's only indented on one side, not both the 
left and right. Finally a way to accomplish this!</FONT>
</BLOCKQUOTE>
This page is shown in Figure 14-1.

[screen shot]
Figure 14.1: The old way to format a page.

This is basic HTML layout that you learned quite a few chapters ago and is not very exciting. Let's stretch things now. It turns out that the second paragraph needs to be double-spaced and the third paragraph should only have an indent on the left side, not both the left and right, as is the wont of the <BLOCKQUOTE> tag. How can you do this?

Inline Style Sheets

The need by designers for this high level of control over the presentation of information is exactly why style sheets are so exciting. With style sheets, we can change the spacing between lines, affect one margin but not others, and much more. Here's the same page as shown earlier, rewritten to include the characteristics desired with style sheets:

Here's a regular paragraph of information.
<P TYPE="text/css" STYLE="font: 12pt/20pt Courier">
This is some code to show, it should be in 'courier' and 
it should have lots of space between the lines of text, 
more than would normally be the case with a 12 point 
typeface.
<P TYPE="text/css" 
    STYLE=" font: 14pt/11pt helvetica; margin-left: 1in; color: red">
And don't forget this important - indented - note too! 
But look, it's only indented on one side, not both the 
left and right. Finally a way to accomplish this!
The changes are actually added as attributes to the specific HTML tags. In this case, these changes are specified in the <P> tag. You can see that there are two new attributes. The first should always be specified with inline style information: TYPE=text/css. The CSS, as you know, means cascading style sheets (I always envision a beautiful waterfall of information cascading down a virtual hillside when I hear the name, I must admit), and the "text" specifies that the style information is specified in text form, which is the only choice, actually.

The second attribute is the actual style specification. In the second line in the above example, the style specifies 12-point Courier with a 20-point leading. The later style specification is a bit more complex: 14-point type with an 11-point leading (which means that the lines will just about overlap), bold, with a left margin 0.5-inch from the edge. The type should also be in red. Figure 14-2 shows the results.

[screen shot]
Figure 14.2: The same document with style sheets

There are things I'm doing on this page with style sheets that can't be done with any HTML, however much you might try. You could get the left indent, for example, by having a 100 percent width zero-border table, and then specify the first column is blank, for spacing, but there's no way to affect the leading of a paragraph of text short of making the text a graphic, which defeats the purpose of the Web.


Note A point is a unit of measurement for type size: 10-point type measures 10 points from the very top of a full-height letter, such as h or a capital, to the bottom of a descending letter such as g, y or p.. Historically, a point was actually the unit of measurement for the metal slug that held the letters on an old-fashioned printing press, if you want to be completely accurate. Nonetheless, it's a very common gauge of type size, and there are 72 points in an inch.

You can control a remarkable range of different page presentation attributes with a style specification, including all of those shown in Table 14-1.

 
AttributeDescriptionValuesExample
backgroundSets background images or colorsURL, color-name, RGB value (hex) {background: white}
colorSets color of textcolor-name, RGB value (hex){color: blue}
font-familySets typeface typeface name or font family name{font-family: courier}
font-sizeSets size of textpoints (pt), inches (in), centimeters, (cm), pixels (px){font-size: 12pt}
font-styleItalicizes textnormal, italic{font-style: italic}
font-weightSets thickness of typeextra-light, light, demi-light, medium, demi-bold, bold, extra-bold{font-weight: bold}
line-heightSets the distance between baselinespoints (pt), inches (in), centimeters (cm), pixels (px), percentage (%){line-height: 24pt}
margin-leftSets distance from left edge of pagepoints (pt), inches (in), centimeters (cm), pixels (px){margin-left: 1in}
margin-rightSets distance from right edge of pagepoints (pt), inches (in), centimeters (cm), pixels (px){margin- right: 1in}
margin-topSets distance from top edge of page points (pt), inches (in), centimeters (cm), pixels (px){margin-top: -20px}
text-alignSets justificationleft, center, right{text-align: right}
text-decorationUnderlines or otherwise highlights textnone, underline, italic, line-through{text- decoration: underline}
text-indentSets distance from left marginpoints (pt), inches (in), centimeters (cm), pixels (px){text-indent: 0.5in}

Table 14-1 Style Sheet Attributes
One more snippet to make sense of the above table. There are six different units of measure you can use with style sheets: "px" is pixels, "in" is inches, "cm" is centimeters, "mm" is millimeters, "pt" is points and "pc" is percentage. Further, text-based measures can also be specified in em spaces with the "em" unit.


Note An em space is traditionally the widest possible character space in a font, it's the width of the capital letter "M". Typographers also pay attention to "N" space (en space) and "I" space.

Now, armed with this table of options, let's try some further tweaking to some Web pages to see what kind of hoops we can make the browser jump through!

When you look at the table above, you might be a bit puzzled by the previous example: most of these specific elements don't appear in the style information shown. That's because you can use a shorthand notation for style sheet information to save lots of typing. Here's an example:

<H1 TYPE="text/css" STYLE="font-weight: bold; 
    font-size: 12pt;
    line-height: 14pt; 
    font-family: helvetica">Important Header</H1>
    
is exactly equivalent to:
<H1 TYPE="text/css" STYLE="font: bold 12/14 helvetica">Important 
Header</H1>
Notice here that we're not specifying a typeface, but rather a font family. There are a small number of font families defined as part of the CSS specification that allow you to avoid worrying about the specifics of exact typeface names on each machine and instead pick the kind of typeface you desire. The families are defined in Table 14-2:

Family NameExemplary TypefaceSample
serifTimesTimes Roman
sans-serifHelveticaHelvetica
cursiveZapf-ChanceryZapf Chancery
fantasyWesternWestern
monospaceCourierCourier

Table 14.2: Generic Font Families

Let's look at another example of inline style modifications:

<H1 TYPE=text/css STYLE="text-align: center; font: 0.5in helvetica; 
color: blue;  border-width: 0.15in; border-color: red; 
border-style: groove">
Corporate Information Center</H1>
versus
<H1 TYPE=text/css STYLE="text-align: center; font: 0.5in serif; 
color: blue;  background-color: yellow; border-width: 0.15in; border-color: red; 
border-style: ridge">
Corporate Information Center</H1>
This takes advantage of some elements that are not widely supported in style sheets. The border of an element can be displayed by specifying its size and some attributes. In this case I've specified that it should be 0.15 inches in size, red, and that the visual appearance of the border should be a "groove" or cutout. Other values include "none," "dotted,""dashed," "solid," "double," "ridge," "inset," and "outset."

Figure 14-3 shows you the wonderful results of this fancy style specification. Notice the difference between the "ridge" and "groove" style of border, and how changing the typeface family from Helvetica (a sans-serif, or no serif typeface family) to the "serif" family has dramatically changed the feel of the second header. Of course, the yellow background helps differentiate the two onscreen, too.

[screen shot]
Figure 14-3: A new way to look at headers.

You're starting to see the amount of control you have with style sheet information. It's really remarkable if you're willing to spend the time to figure it out. Here's another example of how I might combine all of these style sheets:

<H1 TYPE=text/css STYLE="text-align: center; font: 0.5in helvetica; 
color: blue;  border-width: 0.1in; border-color: #999999; 
border-style: inset">
The Winter's Grove</H1>
<P TYPE=text/css STYLE="text-align: justify; font: 14pt/17pt;
border-width: 0.15in; border-color: #CCCCCC; border-style: double;">
It was a cool evening and I was sitting on the stoop, 
wondering whether to finish the shed roof or enjoy the 
companionship of the dogs, sprawled at my feet. All at 
once a bright light shone at the eastern edge of the 
forest followed almost immediately by a loud crack, as if 
the heavens themselves had suddenly been split asunder.
I jumped up following my dogs, who had already begun 
barking and running towards the strange phenomenon.
</P>
So begins the first chapter of ...
I have to admit that working on these examples has proven highly frustrating because not only do the different browsers support different pieces of style sheets, but with Navigator, if you have anything that diverges even slightly from the standard it understands, it'll ignore everything in your style specification. Explorer is much friendlier, ignoring what it doesn't understand and showing you the results of everything else.

You can see the difference between the two in figures 14-4, 14-5, 14-6 and 14-7, which show exactly the same page displayed in Internet Explorer on Windows 95, Netscape Navigator on Windows 95, Internet Explorer on the Macintosh and Netscape Navigator on the Macintosh.

[screen shot]
Figure 14-4: Styles rendered in Navigator 4.0 on Windows 95

[screen shot]
Figure 14-5: Styles rendered in Internet Explorer 4.0 on Windows 95

[screen shot]
Figure 14-6: Styles rendered in Navigator 4.0 on the Macintosh

[screen shot]
Figure 14-7: Styles rendered in Internet Explorer 4.0 on the Macintosh.

Style sheet specifications clearly offer considerable power -- even if the results are quite different on the different possible browsers -- but having to add all these tags on every single HTML tag would make this quite a hassle. The good news is there are two important alternatives. Having the style information within a specific HTML tag is known, as I said, as "inline" style information, but in fact there are three different ways to specify styles in your documents: inline, within the document header, and with an external style sheet.

Header Styles

You've already seen how to specify style specifics within an HTML tag, but the good news is you can actually redefine HTML tags at the top of your document and then have the changes apply to all uses of that tag within the page.

For example, say you want to have all header-level-one tags in 28-point Arial, green, and center aligned. Here's the style tag:

<STYLE TYPE="text/css">
<!--
   H1 { font: 28 pt "Arial Black"; color: green; text-align: center }
-->
</STYLE>
Once you've created this definition, every use of the <H1> tag in your document will produce the style specified in the header.

Worth noting is that the <STYLE> tag wraps all style definitions, but older browsers might try to actually display the style definition itself, so, like scripting inclusions, style definitions should be wrapped in HTML comments.

There's even a shorthand way for specifying some of these style characteristics. If you want to specify a variety of font details, you can pour them all into one tag:

H1 {font: 15pt/17pt "Arial Black" }
You can also create your own types of HTML tags by using classes within style sheets.

Let's say that I want to have two paragraph styles, one that includes code listings (just like this book!) and another that includes handy notes shown in red. I could do this with style sheets as:

<STYLE TYPE="text/css" >
  P.code { font: 12pt/20pt "Courier" }
  P.notes { font: 14pt/16pt; margin-left: 0.5in; color: red }
</STYLE>
Now you can use this within your own documents as shown with yet another rewrite of the first example page:
<STYLE TYPE="text/css" >
  P.code { font: 12pt/20pt "Courier" }
  P.notes { font: 14pt/16pt; margin-left: 0.5in; color: red }
</STYLE>
<P>
Here's a regular paragraph of information.
<P CLASS=code>
This is some code to show, it should be in 'courier' and 
it should have lots of space between the lines of text, 
more than would normally be the case with a 12 point 
typeface.
<P CLASS=notes>
And don't forget this important - indented - note too!
You can see how this could let you have attractive and very consistent Web pages across various sites. See Figure 14-8 for an example of how this formats.

[screen shot]
Figure 14-8: Classes of HTML tags with style sheets

Now you can see what's cool about this: With a slight modification to the top of the document, all the material in the Web page is automatically changed. No tedious item-by- item modifications. For example, I'll change the top STYLE definition to the following:

<STYLE TYPE="text/css">
  P.code  { font: 16pt/20pt cursive; margin-left: 1in; background=#cccccc }
  P.notes { font: 18pt/20pt; color: red }
</STYLE>
Consider how differently the Web page now displays on the screen, as shown in Figure 14-9.

[screen shot]
Figure 14-9: Same HTML, different style sheet.

External Style Sheets

Having all your styles specified at the top of the page can be a real time saver and ensure a high level of consistency throughout the document, but if you have a multipage Web site, you'll be delighted to know that you can actually have a single style sheet for an entire site. The style sheet is saved as a ".css" document and is referenced within the header of each page that needs it:

<HEAD>
<TITLE>Nine Reasons to Stay In Durango, Colorado</TITLE>
<LINK REL=STYLESHEET 
      HREF="http://www.intuitive.com/stylesheet.css" 
      TYPE="text/css">
</HEAD>
Here the style sheet is saved as the document http://www.intuitive.com/stylesheet.css on my server.

Cool Style Sheet Tricks

There's a lot more to style sheets that's worth exploring, but we're still a bit ahead of the game -- it's hard to find a Web browser that even implements the majority of the possibilities as defined in the CSS specification, let alone all of them.

Nonetheless, there are some fun things you can try in your Web pages using the various style sheet attributes.

Links change size

Have you always wanted to have links shrink when visited? You can do that using some style specifications:

<STYLE TYPE="text/css">  
  A:link     { font-weight: bold; font: 18pt "Arial Black";  color: blue; }       
  A:visited { font-weight: lighter; font: 14pt "Times Roman"; color: black; }
</STYLE>
You don't have to look too closely at Figure 14-10 to see the difference between the link you've seen and the one you haven't.

[screen shot]
Figure 14-10: Links change size when visited.

Text superimposed

Another part of the CSS specification that I haven't talked about too much herein is the ability to gain fine control over the placement of items, even to superimpose or overlap material.

<STYLE TYPE="text/css">

#background {
  color: #9999CC; 
  font: 100px Impact, sans-serif;
}
#foreground {
  color: #000000; 
  font: italic 30px Georgia, serif;
}

</STYLE>
<BODY BGCOLOR=white>

<P ALIGN=center>
<SPAN ID=background>Meet the Gang</SPAN>

<P TYPE="text/css" STYLE="margin-top: -48px;text-align: center;">
<SPAN ID=foreground>Dave, Linda, Ashley, Jasmine & Karma</SPAN>

<P STYLE="text-align: center; font: bold 20pt serif" TYPE="text/css">

Overlapping text without any graphics. Very nice.

Before I talk about what I'm doing in this particular example, have a peek at Figure 14-11 to see the excellent output of this particular use of style sheets.

[screen shot]
Figure 14-11: Overlapping text

Nice, eh? The most important style sheet attribute I'm using here is the specification "margin-top: -48px" which indicates that the top of the subsequent information should be 48 pixels higher than normal. Since the background words are 100 pixels high ("font 100px") that means we're almost exactly over the lower half of the background letters.

I'm also taking advantage of another way you can use style sheets: Using the ID attribute, I've created another kind of style sheet specification to use, almost a macro, if you're familiar with programming MS Word or similar programs. Exactly the opposite of internal anchors, IDs are defined by prefacing the definition with '#' within the <STYLE> tag, then used with "id=name" later in the HTML.

Finally, a tag that really has no value other than in this kind of context: the <SPAN> tag by itself doesn't change the presentation of information on your page, but lets you specify attributes for any text within. In this case, I'm using this to utilize the style IDs already defined.

TagClose TagMeaning
<STYLE</STYLE>Style sheet information specified..
TYPE=valType of style sheet. Usually "text/css."
<SPAN></SPAN>Generic HTML range tag, for styles only

Table 14-2 HTML Tags Covered in This Chapter
Summary
This chapter gave you a good idea of the future of much of HTML: Style sheets give you a remarkable amount of control over the layout and appearance of your content. It was also clear as you went along, however, that style sheets are still part of the future, because even the most recent browsers don't agree on the CSS format and on which styles they can interpret correctly. Chapter 15 continues the exploration of the HTML 4.0 specification by looking at how they've improved tables and frames for designers.
    ---

    navigational options

View Source