Creating Cool Web Sites
Sample Book Chapter
Chapter 4: Moving into the 21st Century with Cascading Style Sheets

After reading the last chapter you might think that text markup is pretty straightforward -- with tags such as <b>, <i>, and the like -- but not very powerful. After all, when you look at Web pages from large commercial sites such as ESPN, Disney, or The Wall Street Journal, you see a variety of typefaces, type treatments, and even line-spacing variations.

So how do the Web site creators accomplish those effects? They use a new and vastly improved addition to Web page design called style sheets. You might be familiar with the concept of style sheets from working with document-processing applications like Microsoft Word, where choosing a particular style produces a complex set of changes in typeface, color, size, indentation, and much more. Style sheets give you a corresponding capability as you design Web pages

One very important characteristic of style specifications, both in applications, such as Microsoft Word, and in Web documents, is that attributes are inherited. Suppose that a paragraph in your document appears in 14-point Times Roman. Then you apply a style to a single word in the paragraph that puts the selected word in blue. Besides having the blue added, that word also inherits the typeface, typeface size, and any other attributes from the parent style applied to the remainder of the paragraph. In Web parlance, this is known as cascading (style attributes cascade down until something changes them). The style sheets I'll be talking about are, therefore, logically called Cascading Style Sheets and succinctly referred to as CSS.

In this chapter, I begin showing you how to interweave traditional HTML tags and formatting (actually, I use XHTML, but for simplicity, every time you see HTML, imagine that you really see XHTML) with the newer, more powerful CSS capabilities. Why weave them together? Because although CSS is wonderful for many things, it frankly requires too much work when you want to make just one or two simple, straightforward changes. If I want a word in bold on my page, it's usually much simpler to specify <b> than to figure out the CSS details.

Types of CSS

Cascading Style Sheets are really a completely different approach to page styling and layout. So first, you need to look at where you add CSS information to your page. CSS information can be specified in three different places:

  • Within the specific tags in the document body
  • At the top of the document within a <style> block, or combined with named <div> or <span> containers in the document body
  • In one or more separate files shared across many Web pages

These may all be combined with a well-defined inheritance (which is why they are called cascading style sheets). Don't worry, this will all make sense as you explore CSS.

Inline CSS

Basically, styles can be specified with the style attribute within almost any HTML markup tag. For example, you can have a bold tag that also changes the color of the text within by using the following HTML:

<b style="color: blue">this is bold and blue</b> and this isn't.

More commonly, styles are used within one of two otherwise empty tags called <div> or <span>. These two tags were introduced into HTML specifically for use with Cascading Style Sheets, so if you see them on a Web page, they're often used like this:

<span style="color:green">this is green</span> and this ain't.

The difference between the two is that <div> is used as a block container (it's basically identical to <p> and </p>) whereas <span> is used within a block (it's more analogous to <b> and </b>).

Take a look at this simple sequence of HTML with a simple style attribute, color:, applied:

<p>
This is a typical paragraph of text that contains
some words, perhaps a sentence or two, but that's
about all.
</p>
<div>
By contrast, this is a <span style="color:blue">vibrant</span>,
<span style="color:red">colorful</span>
<span style="font-family: monospace">div</span> block
that has lots of room for growth!
</div>

The result of having this code interpreted by Microsoft Internet Explorer is shown in Figure 4-1.

[figure 4-1]
Figure 4-1: Rudimentary style sheets aren't too thrilling. Yet.

The preceding example is not going to convince you that this approach is superior to the <font> tag discussed in Chapter 3. But read on, and perhaps you will begin to understand the value of style sheets.

One definition, many references

The second way to work with CSS will doubtless catch your attention. To a great extent, CSS enables you to redefine how any HTML markup is rendered. CSS also essentially allows you to create your own tags to transform a Web page into exactly the format and layout you seek.

This is accomplished by moving the style specifications into a <style> block. At the top of a page, the <style> tag might look like this:

<style type="text/css">
b { color: blue }
</style>

This style specifies that throughout the subsequent document body, all occurrences of the bold tag <b> should also have a type color change to blue. Are you starting to see where this can make your life considerably easier?

More interestingly, you can specify style classes, which are akin to subtags. Imagine that I have a Web site that talks about my digital camera, a Nikon. I'm going to write about how it compares to other digital cameras, including those from Canon, Sony, and Kodak. To make the page consistent, each time that I mention a manufacturer I want to use the identical format. Here's how I can do that with CSS:

While a variety of companies manufacture digital
cameras, notably including
<span class="manuf">Kodak</span>,
<span class="manuf">Olympus</span> and
<span class="manuf">Sony</span>,
there are only two companies that offer true
digital single lens reflex (SLR) cameras:
<span class="manuf">Nikon</span> and
<span class="manuf">Canon</span>.

This gets interesting when you go into the <style> block and specify exactly how to format the manufacturer names. Because these are all specified by class, the CSS notation is to preface the classname with a dot in the style block:

<style type="text/css">
.manuf { font-size: 125%; color: green }
</style>

Figure 4-2 shows the results of using this code at the top of your page.

[Figure 4-2]
Figure 4-2: Classes let you organize your data presentation.

The more I look at Figure 4-2, the more I think, "That's not really quite what I want." Here's where the power of CSS makes things a breeze. To change the style of all the manufacturer names instantly, I simply edit the style definition in the style block. A few changes (don't worry, in a page or so I'll talk about the specific style attributes you can use) and suddenly the Web page is totally different! Here's my modified code:

<html>
<head>
<title>Moving Styles To the Top</title>
<style type="text/css">
.manuf { color:blue; font-weight: bold; font-style: italic }
</style>
</head><body>
While a variety of companies manufacture digital
cameras, notably including
<span class="manuf">Kodak</span>,
<span class="manuf">Olympus</span> and
<span class="manuf">Sony</span>,
there are only two companies that offer true
digital single lens reflex (SLR) cameras:
<span class="manuf">Nikon</span> and
<span class="manuf">Canon</span>.
</body>
</html>

Figure 4-3 shows the result of this code. Remember, the only difference between Figure 4-2 and Figure 4-3 is what's specified in the style block. I know that you can't see the result of the color attribute in this black-and-white screen shot, but I think you can still see that quite a difference results from such a simple change.

[Figure 4-3]
Figure 4-3: Same HTML page, different style specification.

I hope that simple example is enough to sell you on CSS as a powerful method for formatting and specifying the presentation of your Web pages!

Sharing a single style sheet

The third way that you can work with CSS is to create a completely separate document on your Web server that includes all the styles you want to use. You can then reference that document within all the Web pages on your site. You may think that having a single style definition at the top of your page makes it easy to manage the layout of that page. Imagine how handy it would be to have a site with dozens (or hundreds!) of pages of material, all using the appropriate div and span tags and classes. Add to that the capability to change the style across all occurrences of a class, on all pages, with a single edit!

To reference a separate style sheet, use the link tag:

<link type="text/css" href="mystyles.css" />

This refers to a separate style sheet called mystyles.css, stored in the same directory on the same server as the page that contains this link reference. You can also use a fully qualified URL. This is how I reference one of my CSS style sheets on my server:

<link type="text/css"
  href="http://www.intuitive.com/library/shared.css" />

The .css file should contain everything you'd otherwise put between the <style> and </style> tags. For the previous example, the entire mystyles.css might look like this:

.manuf { color:blue; font-weight: bold; font-style: italic }

As you develop your site, your shared CSS files will doubtless become longer and longer as you push more of the formatting details into style specifications and out of the HTML tags.

TIP: You can edit separate CSS files in NotePad or TextEdit, and they should be saved with a .css filename suffix. For example, styles.css is a common name, and you would include it in your HTML file with this <link type="text/css" href="styles.css" /> tag.

The Components of CSS

Whether it appears in a style attribute of an HTML tag, within a style block on the top of a Web page, or in a separate document, all CSS specifications have the same general format: name colon value semicolon

Here's an example: color:blue;.

TIP: The very last CSS specification in a group can have the trailing semicolon omitted because there's nothing subsequent; but it's a good habit to always use a semicolon after each style specification. CSS specifications are case-insensitive, but by convention you should use all lowercase, just as XHTML specifies all lowercase for the HTML tags.

Within a style block or separate style sheet, tags have style attributes defined within a curly-brace pair, as in the following example.

b { color: green; }

This code adds a shift to green text for any bold passages in the applicable text.

Caution: Within a style attribute, the content that the style changes is already implied by the usage, so no tag names and curly braces are allowed. You can't do the following, for example:
<b style="i { color: yellow; } color:red">this is red</b>
but <i>this should be yellow</i>, shouldn't it? If you're trying to accomplish anything like this, the specification belongs in the style block instead.

Classes and IDs

I have already briefly discussed classes and how you can use them to group similarly formatted content. But there's another type of identifier that you can use in CSS work called an id attribute. You use classes and id tags in similar ways:

<div class="para">
This is a standard paragraph on this page, with
<span id="emphasize8">nothing</span>
out of the ordinary.</div>

Within the style block, these two identifiers are differentiated by their first character: a dot for a class identifier, and a hash mark (#) for an id tag:

<style type="text/css">
.para { font-size: 110% }
#emphasize8 { font-weight: bold }
</style>

The primary difference between these two is that each unique id tag value is supposed to occur once and only once within a given document, whereas classes are reused as needed. In practice, almost every CSS site I've seen makes heavy use of classes and completely ignores id tags.

Subclasses

Another tremendously powerful trick you can use with CSS is to specify subclasses and to constrain formatting styles to a subset of your tags. For example, imagine a Web page like this:

<div class="special">
This is a special block and <b>bold</b> words should appear
differently than they do in regular text.</div>
<p>
And this, by contrast, is regular <b>bold</b> text,
with a little <i>italics</i> tossed in for luck
and an example of <b><i>italics within bold</i></b>.
</p>

To specify that only the bold tags within the class special should have a particular style, use the format class class (in the example below, notice that the b i sequence changes italics within bold sequences only):

<style type="text/css">
.special b { color: green; font-size: 125%; }
b i { background-color: yellow; }
b,i { font-weight: bold; color: blue; }
</style>

Look closely to see what's specified here. Two lines contain a pair of selectors separated by a space; on the third line, the selectors are separated by a comma. On the two lines in which a space separates the selectors, the second selector is affected only when it falls within the first selector. In other words, bold text is green only when the <b> is used within a class="special" block, and the background color is yellow only when the <i> is used within a <b> tag. In the last of the three CSS lines, I employ a shorthand to specify that both bold tags and italic tags should be in bold with blue text. It's the same as if I had used b { ... } and i { .... }.

Put this all together and the results are as shown in Figure 4-4.

[Figure 4-4]
Figure 4-4: Subclasses and special selectors allow very specific control over styles.

If you're starting to think, "Hey, this stuff is pretty darn powerful," you're right! CSS is a thousand times more powerful than even the fanciest HTML formatting, and there's no question that it's the future of Web page design and layout. The price, as you can already see, is that it's more complex. There is quite a bit of difference between <b>bold</b> and <span style="font-weight: bold;">bold</span>, but stick with me and you'll get the hang of things. You may soon find that you are creating exceptional pages -- and with darn little work!

Adding comments within CSS

Here's another little tip: You can add comments to your CSS in two different ways. For a single-line comment, use two slashes; anything after them is ignored through the end of the line, as in the following example:

b { font-weight: normal; } // disabled bold for this page

If you need a multiline comment, wrap it in /* and */ pairs, as shown in the following example:

<style type="text/css">
b { font-weight: normal; }
/* The head of layout suggested that we disable all bold text as
an experiment, so we've done so. - DaveT, Oct 11 */
</style>

Compatible style blocks

If you're big on backwards compatibility, consider wrapping all your style blocks as I have in the following example:

<style type='text/css">
<!--
b { font-weight: normal; }
// -->

</style>

If the Web browser understands style sheets, it ignores the comment characters, and if the browser doesn't understand CSS, it assumes that all the stuff within the <!-- and --> span is a comment and hides it from the final rendered page. In fact, even without CSS, you can always add comments to your HTML pages by surrounding them with <!-- and -->. They show up in the source code but aren't displayed in the actual Web page you see in a browser.

NOTE: I have to admit that I typically do not use the comment sequence to hide my style blocks. CSS-compatible Web browsers first came out in 1997, so by this point, the vast majority of users should have browsers that can render CSS properly. You can make your own call, however, as there are definitely different opinions on this subject.

Text Formatting with CSS

You've looked at the skeleton of CSS long enough; it's time to dig into some specifics of CSS formats and styles! To parallel Chapter 3, I start with basic text transformations: bold, italics, colors, sizes, and typefaces.

Bold text

The most straightforward of the CSS visual text formatting styles is bold, which is specified as font-weight. As with all CSS tags, you can define a variety of possible values:

  • lighter
  • normal
  • bold
  • bolder

You can specify the weight of the font in increments of 100, in the range of 100@@nd900, with 100 being the lightest and 900 being the heaviest. Normal text is weight 500, and normal bold is 700. Specifying font-weight: 900 is the equivalent of extra-bold or, in the parlance of CSS, bolder.

Italics

Italics are easier to work with than bold. You simply specify a font-style and pick from one of the following values:

  • normal
  • italics
  • oblique
Note: Oblique font style is similar to italics, but more slanted. On a Web page, however, it looks identical to italics.

Why have a value for normal? Answering this question reveals the secret magic of the cascading of style sheets. Imagine the following:

<div style="font-style: italics">
This is a paragraph where all the words should be italicized.
But what if I have a word that I don't want in italics?
</div>

If you want don't to appear in a non-italics format, the easiest way to accomplish this is to use font-style: normal to override the italics formatting. In fact, this does the trick:

<div style="font-style: italics">
This is a paragraph where all the words should be italicized.
But what if I have a word that I
<span style="font-style:normal">don't</span>
want in italics?
</div>

This is the same reason that the font-weight style has a normal value.

Changing Font Family, Size, and Color

As I've shown you so far in this chapter, switching between bold and italics within CSS is straightforward. Other text transformations, such as changing the font family, the font size, and the color, are also easy to do, and the following sections show you how.

Typefaces and monospace

With standard HTML markup, the <tt> tag produces typewriter text, but call it by its proper name: monospace. Chapter 3 talks about the difference between monospace and proportional spaced typefaces. CSS is much more accurate about this particular text transformation because it's really a typeface change . . . well, a font-family change, to be precise.

NOTE: All right, I'll call the change in typeface produced by a font-family style what Web standards developers want me to call it, a font; but it's really not. A font is a specific applied instance of a typeface, style, and size. Times Roman is a typeface, for example, but Times Roman 12 point, oblique, is a font.

At its most basic, the font-family style enables you to specify one of a variety of different typeface families:

  • serif
  • sans-serif
  • monospace
  • cursive
  • fantasy

The most commonly used font families on the Web are serif (typically Times Roman or Times) and monospace (typically Courier). Times Roman is the default typeface used by Web browsers, and Courier is used to show code listings and form input fields.

The font-family style enables you to specify a typeface by name, or even indicate a list of typefaces separated by commas, exactly as the face attribute of the font tag does in plain HTML.

Here's how you might use the font-family style in practice (with some additional styles thrown in for fun):

<style type="text/css">
b { color: blue; font-style: italic; }
i { color: green; font-family: Monotype Corsiva,cursive;
    font-style: normal; }
tt { font-family: serif; background-color: yellow; }
.mytt { color: red; font-family: monospace; font-weight: bold; }
</style>
</head><body>

<div>
This is <b>a bit of bold text</b>, with a little <i>content
displayed in italics</i>
tossed in for luck, and a <tt>monospace</tt> passage too, which
should be compared to
<span class="mytt">this tt 'emulation' passage</span>!
</div>

All these changes are displayed in Figure 4-5.

[Figure 4-5]
Figure 4-5: Adding color, font-style, and font-family styles makes an interesting page.

In the code shown for Figure 4-5, notice especially that you can redefine the browser's default rendering of HTML tags by redefining their style within CSS. In this case, I effectively removed the monospace typeface change from the <tt> tag. However, if you have sharp eyes, you can see that the resulting serif content (the word monospace) is slightly smaller than the surrounding text because the Times Roman typeface is naturally smaller than Courier. In addition, I set the background to yellow, too. The size change you can fix with the font-size style, as you see momentarily.

Changing font size

As I've shown you in some of the earlier examples in this chapter, you use the CSS font-size style to change the size of text. This style accepts specific sizes in a variety of units (see Table 4-1) or the following specific named values:

  • xx-small
  • x-small
  • small
  • medium
  • large
  • x-large
  • xx-large
and two relative sizes:
  • smaller
  • larger

Finally, you can also specify a font size by percentage: A specification of font-size: 110% means that it's 10% larger than the text would otherwise be displayed. If the 110% appears within an h1 passage, for example, it produces a larger end result than if it's in a p or div block.

Measure Definition Comment
in inches A measurement that can prove problematic with layout, although people commonly use it. To understand why, try to figure out what 1in becomes if you're simultaneously looking at a page on a computer monitor and projecting it on a screen through an LCD projector.
cm centimeter The same problem as with inches; of course, a different measurement.
mm millimeter Same problem as with inches.
pt points A traditional typographic unit. There are 72 points to an inch. You see these measurements a lot because that's the mystery value whenever you talk about a typeface as 18 point (which you describe in CSS as 18pt). For display use, this measure poses the same problem as the preceding measurements.
pc pica Another traditional typographic unit of measure: 1 pica = 12 points = 1/6 inch, or 6 picas = 1 inch. Presents the same problem as the other physical-unit measurements.
em em-width This measure is relative to the size of the current typeface in use; it's the width of the letter m in the specific typeface.
px pixel The size of a specific dot of information on-screen, this measure works great for screen displays, but you must redefine it for printers to avoid startling and unexpected results. Consider that a typical screen is 72@@nd75 dpi, so each pixel is 1/72nd of an inch. On a typical modern printer, however, output renders at 300@@nd600 dpi, so each pixel is 1/300th of an inch or smaller. Most browsers sidestep this by multiplying out the difference, so 10px is actually 40px for printing.
Table 4-1: CSS Size Specifications

These give you a lot of different ways you can specify the type size. I would say that at least 99% of the time, I just use percentage specifications and ignore all these other possibilities. To jump back to my attempt to emulate the <tt> tag earlier, here's a better definition:

.mytt { color: red; font-family: monospace; font-weight: bold;
    font-size: 90%; }

Well, this isn't a complete emulation, of course, because I've specified the content should be red and in bold too, but the monospace type is now displayed at 90% of the size of the regular text on the page. Better yet, it's true regardless of what size type I'm working in:

<h2>This is <span class="mytt">my big tt</span> and</h2>
This is smaller <span class="mytt">my tt</span> text.

The color of text

Surprisingly, you don't change the color of text with a style called font-color. Given that every other style modification is done with font-something, it took me a while to remember that color is changed by simply using the attribute color:. Throughout this chapter, I have shown many examples of color specifications, but they've all been specific by color name. In fact, there are a bunch of ways you can specify a color within CSS, some of which are explained in more detail in Chapter 7, and all of which are listed in Table 4-2.

Specifier Example Comment
#RRGGBB #009900 This notation is the color specification that you've been using for a long time if you're an HTML coder. It's a two-hexadecimal@@nddigit red, green, and blue value, where 00 is the least of a color and FF is the most. It offers more than 16 million possible colors and is explored in detail in Chapter 7.
#RGB #090 A useful variant on the regular #RRGGBB scheme, this specification duplicates each of the values to create a six-digit color. The #090 value, therefore, is identical to #009900. It offers more than 4,000 different possible colors. Although if you stick to the so-called Internet-safe color palette (explained in Chapter 7), you need only 216 colors (the values of #0, #3, #6, #9, #C, and #F for each of red, green, and blue).
rgb(r%,g%,b%) rgb(0%,100%,50%) An unusual notation, in which you specify integer color values for each red, green, and blue component. It offers exactly one million possible colors.
rgb(rr,gg,bb) rgb(128,0,128) Similar to the previous notation, this specification enables you to use integer color values, but the value can range from 0@@nd255. If you do the decimal to hexadecimal math, you find that the two-digit hex notation #RRGGBB offers exactly the same number of choices, just in a different way. It offers more than 16 million possible colors.
colorname Blue The CSS standard defines 16 colors by name, and they're the 16 colors of the original Windows VGA palette: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. Some browsers can recognize more color names, but the specification includes only these 16.
Table 4.2: Color Specification Options in CSS

Additional Neato Text Tricks in CSS

Before I wrap up the discussion of text transformations in CSS, take a peek at a number of additional styles that are available to change how the text on your Web page appears -- transformations that aren't possible in regular HTML.

Small capitals

One of the most interesting styles accessible in CSS is the capability to specify a font-variant that has every letter capitalized, with the letters that were already capitalized slightly larger than the lowercase letters capitalized by the variant. Here's a typical usage:

<style type="text/css">
.smallcap { font-variant: small-caps; }
</style>
</head><body>

<h1>This is a Level One Header</h1>
<h1 class="smallcap">This is also a Level One Header</h1>

The CSS specification defines a number of possible font variants, but so far Web browser developers seem to have implemented only small-caps. The other possible value, to shut off small-caps, is normal.

Stretching or squishing letter spacing

Another interesting variation in font layout is the letter-spacing style, which enables you to expand or compress type by a specified per-letter value -- even if it causes letters to overlap! Adjusting this space between letters is known as kerning in typographical circles. Here's an example:

<h1 style="letter-spacing: -2px;">And Another Level One Header</h1>

Figure 4-6 shows small-caps and letter-spacing all on the same page.

[Figure 4-6]
Figure 4-6: Small caps and letter spacing offer interesting type variations.

You can use any of the units specified in Table 4-1 in the letter-spacing style. In this example, I'm indicating that each letter should have two pixels less space for width than normal, effectively compressing the text just a bit.

Stretching or squishing words

If you don't want to have the spacing between letters adjusted, but you still want some control over the overall width of a text passage, word-spacing might be just what you need. Consider the following example:

.wide { word-spacing: 15px; font-weight: bold; }
.narrow { word-spacing: -3px; font-weight: bold; }

Be careful with these values, especially if you're trying to compress the text! A little change can quickly produce unreadable text, and just a bit more can cause words to overlap.

Changing line height

The height between the lines of text in a paragraph is known as leading. You probably remember having to write double-spaced papers in school. Double-spaced, in CSS terms, is line-height: 2. Unusual in a CSS style, line-height doesn't need a unit (unless you want to refer to percentages, inches, pixels, points, and so on) and accepts fractional values, too. So to get a line-height half way between single-spaced and double-spaced, use line-height: 1.5, as shown:

.doublespaced { line-height: 1.5; }

Putting it all together, here's an example of line-height and word-spacing:

<style type="text/css">
.wide { word-spacing: 15px; font-weight: bold; }
.narrow { word-spacing: -3px; font-weight: bold; }
.doublespaced { line-height: 1.5; }
</style>
</head><body>

<div class="doublespaced">
This is a paragraph of text that's double-spaced. This means
that the <i>leading</i>, or interline spacing, is different
from standard text layout on a Web page. Within this
paragraph, I can also have
<span class="wide">some words that are widely spaced due to
the word-spacing value</span> and, of course,
<span class="narrow">some words that are narrowly spaced,</span>
too.
</div>
<p>
By comparison, this paragraph doesn't have any special line-height
specified, so it's "single spaced." Notice the difference in the
space between lines of text.
</p>

The effects of both word and line spacing are shown in Figure 4-7.

[Figure 4-7]
Figure 4-7: Word and line spacing can dramatically change the way text looks on a page.

Not all possible settings are good, of course. A line height that's too small results in the lines of text becoming illegible as they're overlapped. The single addition of line-height: 1.25, however, can significantly improve the appearance of a page, and you can increase line height for the entire document by changing the style of the body tag. Adding the following code to the top <style> block changes all the text on the page:

body { line-height: 1.25 }

Cool, eh? I tweak the body container again and again as I proceed. It's very useful!

Text alignment

HTML includes some attributes for the <p> tag that let you specify if you want the text to be left, center, or right aligned, or justified, where both the left and right margins are aligned. These attributes are replaced in CSS with the text-align style, which has the following possible values:

  • left
  • right
  • center
  • justify

Vertical text alignment

Here's one feature that you don't see in HTML except in the exceptionally awkward form of <sup> and <sub> for superscripts and subscripts, respectively. Instead, use vertical-align and pick one of the values shown in Table 4-3.

Value Explanation
top Specifies that top of element aligns with top of highest element in line
middle Specifies that middle of element aligns with middle of line
bottom Specifies that bottom of element aligns with bottom of lowest element in line
text-top Specifies that top of element aligns with top of highest text element in line
text-bottom Specifies that bottom of element aligns with bottom of lowest text element in line
super Indicates superscript
sub Indicates subscript
Table 4.3: CSS Vertical Alignment Values

A nice demonstration of this capability is a technique for having trademark (tm) character sequences displayed attractively on a page:

.tm { vertical-align: top; font-size: 33%; font-weight: bold; }

In use, this might appear as:

Though just about lost to common parlance, it remains the case that
Xerox<span class="tm">tm</span> is a trademark of Xerox Corporation.

Text decorations

One HTML text decoration that, surprisingly, made it to CSS is underlining. As discussed in Chapter 3, underlining text on a Web page is somewhat problematic because it can become quite difficult to differentiate links from underlined text. But the CSS text-decoration style enables more than just underlining. It provides the following four values:

  • underline
  • overline
  • line-through
  • blink

With the exception of overline, these all have HTML equivalents: <u> for underline, <strike> for line-through, and <blink> for blink. In CSS, however, it's much easier to apply a number of them simultaneously, like this:

h1 { text-decoration: overline underline; }

By using the underlining styles, you can rather dramatically change the appearance of headers throughout a document.

Changing text case

This is the last new CSS style for this chapter, I promise. I know that this chapter must seem like quite a monster with all this thrown at you at once! That's why it's incredibly important that you try things on your computer as you read about them. If you just sip your latté while you go through this book, your retention is likely to be minimal. But if you're trying each and every style and example on your computer, you'll have lots of "a ha!" moments, and you should start to see the tremendous value of CSS for even the most rudimentary pages.

On the Web: Don't forget, all the code listings are available on the book Web site at http://www.intuitive.com/coolsites/.

The final style to learn in this chapter, text-transform, deals with the capitalization of text and has the values specified in Table 4-4.

ValueMeaning
capitalize Displays the first letter of each word as caps and all others as lowercase
uppercase Displays all letters as uppercase
lowercase Displays all letters as lowercase
none Displays characters as specified
Table 4-4: Text Transformation Values

To have a paragraph of text transformed into all uppercase, for example, use text-transform: uppercase;, and to instantly ensure that all header level ones are in proper case, use:

h1 { text-transform: capitalize; }

Putting it all together

Let's pull the example from the end of the last chapter and see how using CSS can help jazz up the presentation. Here's what I've produced with just a little CSS tweaking (notice that I always include a font-family default value, too):

<style type="text/css">
body { font-family: Arial,Helvetica,sans-serif; font-size:90%;
    line-height: 1.25; }
h1 { text-transform: capitalize; text-decoration: overline
    underline; color: blue; letter-spacing: 0.05em; text-align: center; }
i { font-variant: small-caps; font-weight: bold; }
.email { color: #909; font-family: monospace; font-size: 90% }
.tm { vertical-align: top; font-size: 40%; font-weight: bold; }
</style>
</head><body>
<h1>Travels with Tintin</h1>
<p>
Of the various reporters with whom I've travelled around
the world, including writers for <i>UPI</i>, <i>AP</i>,
and <i>Reuters</i>, the most fascinating has clearly been
<b>Tintin</b>, boy reporter from Belgium (
<span class="email">tintin@intuitive.com</span>).
</p><div style="text-align:right">
Probably the most enjoyable aspect of our travels was his
dog <b>Snowy</b>, though I don't know that our hosts would
always agree!
</div>
<h1>The First Trip: Nepal</h1>
<p>
After winning the Pulitzer for <i>Red Rackham's Treasure</i>
<span class="tm">tm</span>,
Tintin told me he wanted a vacation. Remembering some of his
earlier adventures, he decided to visit Nepal. Early one
Sunday, I was sipping my tea and reading the <i>Times</i>
when he rang me up, asking whether I'd be able to take a
break and come along...
</p>

Check out the attractive result in Figure 4-8. Make sure you compare this figure to Figure 3-8 from the previous chapter to see how much more capability you've gained by moving to CSS.

[Figure 4-8]
Figure 4-8: The Travels With Tintin screen shot from Chapter 3 has been enhanced with the CSS styles presented throughout this chapter.

TIP: One CSS shortcut that I haven't mentioned here is the font: style itself. Many of the individual font-related styles can be combined into a single font: style, saving you a lot of work. For example, the following two code lines are functionally equivalent:

h1 { font-weight: bold; font-size: 22pt;
    line-height: 30pt; font-family: Courier, monospace; }
h1 { font: bold 22pt/30pt Courier, monospace }

Well worth learning to save you typing!

TagClosing TagDescription
<span </span> Specifies a nonbreaking CSS container; used within sentences or headers to change individual words
  style= Provides specific CSS styles to apply to the span
  class= Identifies which CSS class should be applied to the span
  id= Identifies which CSS ID should be applied to the span
<div </div> Specifies a CSS container that acts identically to the <p> tag; forces a line break before and after
  style= Specifies CSS styles to apply to the div
  class= Identifies which CSS class should be applied to the div
  id= Identifies which CSS ID should be applied to the div
<link References external CSS style sheet by name
  type= Specifies a type of external link; for CSS it should be text/css
  href= Indicates the URL of the style sheet; by convention, separate CSS style sheets are named with a .css filename suffix
<style </style> Specifies a block for CSS style definitions on Web page; should appear within the <head></head> block of the page
  type= Specifies the type of style sheet being used; for CSS always use text/css
Table 4-5: HTML Tags That Support CSS Covered in This Chapter

Style Exemplary UsageDescription
font-weight font-weight: bold Specifies how much or how little to embolden a text passage
font-style font-style: italic Specifies whether to italicize, oblique, or leave the text passage non-italicized
font-family font-family: serif Specifies which typeface to use for the text passage, as a comma-separated list, or which font-family to use from a small predefined list
font-size font-size: 80% Specifies the type size of the text passage in one of a wide variety of different units and values
color color: green Specifies the text color in the text passage; can be color names or color values specified in a variety of ways
font-variant font-variant: small-caps Transforms the text passage based on the specified variation; only small-caps and none are defined
letter-spacing letter-spacing: -3px Changes the interletter spacing (also known as the kerning) to make it larger or smaller than the default
word-spacing word-spacing: 15px Increases or decreases the spacing between words in the text passage
line-height line-height: 1.25 Changes the spacing between lines of text (also known as the leading); a variety of values are accepted, including fractional values such as 1.5 (for one and a half times normal spacing), 2 (for double spacing), and so on
text-align text-align:center Specifies alignment for a block of text
vertical-align vertical-align: sub Specifies vertical alignment of a text passage relative to other text on the line
text-decoration text-decoration: underline Specifies one or more of a variety of simple text decorations
text-transform text-transform: capitalize Specifies one of a number of text transformations involving upper- and lowercase letters
font font: 22pt monospace Indicates shorthand CSS notation that allows the specification of a number of different font characteristics
Table 4-6: CSS Styles Covered in This Chapter

Summary

This chapter introduced you to the marvels of Cascading Style Sheets, showing you how a few simple changes to your HTML, such as bold, italics, underlining, text alignment, and text decorations and transformations, can result in dramatically improved Web page layout and text presentation. In the next chapter, you continue your exploration of both HTML and CSS by looking at lists and special characters.

Excerpted from Creating Cool Web Sites with HTML, XHTML, and CSS by Dave Taylor. Copyright © 2005 by Wiley Publishing, Inc. All rights reserved. Reproduced here by permission of the publisher.




Valid XHTML 1.0!     Valid CSS!

You're visitor # to this web site.