BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Cascading Style Sheets: The Definitive Guide
Cascading Style Sheets: The Definitive Guide

By Eric A. Meyer

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: HTML and CSS
In many ways, the Cascading Style Sheets (CSS) specification represents a unique development in the history of the World Wide Web. In its inherent ability to allow richly styled structural documents, CSS is both a step forward and a step backward—but it's a good step backward, and a needed one. To see what is meant by this, it is first necessary to understand how the Web got to the point of desperately needing something like CSS, and how CSS makes the web a better place for both page authors and web surfers.
Back in the dimly remembered early years of the Web (1990 -1993), HTML was a fairly lean little language. It was almost entirely composed of structural elements that were useful for describing things like paragraphs, hyperlinks, lists, and headings. It had nothing even remotely approaching tables, frames, or the complex markup we assume is a necessary part of creating web pages. The general idea was that HTML would be a structural markup language, used to describe the various parts of a document. There was very little said about how these parts should be displayed. The language wasn't concerned with appearance. It was just a clean little markup scheme.
Then came Mosaic.
Suddenly, the power of the World Wide Web was obvious to almost anyone who spent more than ten minutes playing with it. Jumping from one document to another was no harder than pointing the mouse cursor at a specially colored bit of text, or even an image, and clicking the mouse button. Even better, text and images could be displayed together, and all you needed to create a page was a plain text editor. It was free, it was open, and it was cool.
Web sites began to spring up everywhere. There were personal journals, university sites, corporate sites, and more. As number of sites increased, so did the demand for new HTML tags that would allow one effect or another. Authors started demanding that they be able to make text boldfaced, or italicized.
At the time, HTML wasn't equipped to handle these sorts of desires. You could declare a bit of text to be emphasized, but that wasn't necessarily the same as being italicized—it could be boldfaced instead, or even normal text with a different color, depending on the user's browser and their preferences. There was nothing to ensure that what the author created was what the reader would see.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Web's Fall from Grace
Back in the dimly remembered early years of the Web (1990 -1993), HTML was a fairly lean little language. It was almost entirely composed of structural elements that were useful for describing things like paragraphs, hyperlinks, lists, and headings. It had nothing even remotely approaching tables, frames, or the complex markup we assume is a necessary part of creating web pages. The general idea was that HTML would be a structural markup language, used to describe the various parts of a document. There was very little said about how these parts should be displayed. The language wasn't concerned with appearance. It was just a clean little markup scheme.
Then came Mosaic.
Suddenly, the power of the World Wide Web was obvious to almost anyone who spent more than ten minutes playing with it. Jumping from one document to another was no harder than pointing the mouse cursor at a specially colored bit of text, or even an image, and clicking the mouse button. Even better, text and images could be displayed together, and all you needed to create a page was a plain text editor. It was free, it was open, and it was cool.
Web sites began to spring up everywhere. There were personal journals, university sites, corporate sites, and more. As number of sites increased, so did the demand for new HTML tags that would allow one effect or another. Authors started demanding that they be able to make text boldfaced, or italicized.
At the time, HTML wasn't equipped to handle these sorts of desires. You could declare a bit of text to be emphasized, but that wasn't necessarily the same as being italicized—it could be boldfaced instead, or even normal text with a different color, depending on the user's browser and their preferences. There was nothing to ensure that what the author created was what the reader would see.
As a result of these pressures, markup elements like <B> and <I> started to creep into the language. Suddenly, a structural language started to become presentational.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
CSS to the Rescue
Of course, the problem of polluting HTML with presentational markup was not lost on the World Wide Web Consortium (W3C). It was recognized early on that this situation couldn't continue forever, and that a good solution was needed quickly. In 1995, they started publicizing a work-in-progress called CSS. By 1996, it had become a full Recommendation, with the same weight as HTML itself.
So what does CSS offer us? As of this writing, it offers us two levels of itself. The first level is Cascading Style Sheets, Level 1 (CSS1), which was made a full W3C Recommendation in 1996. Soon thereafter, the W3C's Cascading Style Sheets and Formatting Properties ( CSS&FP) Working Group got to work on a more advanced specification, and in 1998 their work paid off when Cascading Style Sheets, Level 2 (CSS2) was made a full Recommendation. CSS2 builds on CSS1 by extending the earlier work without making major changes to it.
The future is likely to see further advances in CSS, but until then, let's go over what we already have.
In the first place, CSS allows for much richer document appearances than HTML ever allowed, even at the height of its presentational fever. CSS contains the ability to set colors on text and in the background of any element; it permits the creation of borders around any element, as well as the increase or decrease of the space around them; it allows authors to change the way text is capitalized, decorated (e.g., underlining), its spacing, and even whether or not it is displayed at all; and many other effects.
Take, for example, the first (and main) heading on a page, which is usually the title of the page itself. The proper markup is:
<H1>Leaping Above The Water</H1>
Now, suppose you want this title to be dark red, use a certain font, be italicized and underlined, and have a yellow background. To do all of that with HTML, you'd have to put the H1 into a table and load it up with a ton of other tags like
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Limitations of CSS
There are a few areas that CSS1 does not address, and therefore are not covered in detail in this book; some of these topics are touched upon in Chapter 10. Of course, even a full-blown CSS implementation, covering all of CSS1 and CSS2, would not meet every request from every page designer in the world. It's worth going through some of the boundaries of CSS.
When you get right down to it, CSS1 is not an overly complicated specification. The entire thing can be printed out in less than 100 pages, and it contains about 70 properties. It is still a very sophisticated and subtle engine, but some areas of web design were omitted from CSS1.
In the first place, CSS1 had almost nothing to say about tables. You might think that you can set margins on table cells, for example—and a web browser might even let you do so—but margins should not be applied to table cells under any circumstances. CSS2 introduced a new set of properties and behaviors for dealing with tables, but as of this writing, few if any of these are supported.
To a certain degree, the omission of tables from CSS1 says a great deal about the feeling many have that tables should never be used to lay out pages. It is felt that floated and positioned elements should do all of the work tables used to do, and more. Whether this premise can be supported is not a discussion I intend to undertake here.
In a similar way, CSS1 contains nothing in the way of positioning. Sure, it's possible to move elements around a little bit, but mostly with negative margins and floating. Everything is, in a sense, relative. CSS2, on the other hand, has three chapters devoted to the visual rendering model, which includes the positioning of elements.
CSS1 makes no provision for downloadable fonts. This leads to a good deal of discussion about how to account for user system configurations and available fonts. CSS2 introduces some font-handling, but even there the issue is not resolved, mostly due to the lack of a widely supported font format. It may be that Scalable Vector Graphics (SVG) will solve some or all of this problem, but it is impossible at this point to say with any certainty.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Bringing CSS and HTML Together
We keep visiting the point that HTML documents have an inherent structure. In fact, that's part of the problem with the Web today: too many of us forget 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've bent, warped, and generally ignored the idea that pages should contain information that has some structural meaning.
However, that structure is an inherent part of the relationship between HTML 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 HTML document and break it down by pieces. Here's the markup, shown in Figure 1-1:
<HTML>
<HEAD>
    <TITLE>Eric's World of Waffles</TITLE>
    <LINK REL="stylesheet" TYPE="text/css" HREF="sheet1.css" TITLE="Default">
    <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...
    </P>
</BODY>
</HTML>
Figure 1-1: A simple document
Now, let's examine each portion of the document.
<LINK REL="stylesheet" TYPE="text/css" HREF="sheet1.css" TITLE="Default">
First we consider the use of the LINK tag. 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. CSS1 uses it to link style sheets to the HTML document; in Figure 1-2, a style sheet called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
In order to facilitate a return to structural HTML, something was needed to permit authors to specify how a document should be displayed. CSS fills that need very nicely, and far better than the various presentational HTML elements ever did (or probably could have done). For the first time in years, there is hope that web pages can become more structural, not less, and at the same time the promise that they can have a more sophisticated look than ever before.
In order to ensure that this transition goes as smoothly as possible, HTML introduces a number of ways to link HTML and CSS together while still keeping them distinct. This allows authors to simplify document appearance management and maximize their effectiveness, thereby making their jobs a little easier. The further benefits of improving accessibility and positioning documents for a switch to an XML world make CSS a compelling technology.
As for user agent support, the LINK element has been universally supported, as have both the STYLE element and attribute. @import didn't fare so well, though, being ignored outright by Navigator 4. This is not such a major tragedy, annoying though it might be, since the LINK element will still let you bring external style sheets into play.
In order to fully understand how CSS can do all of this, authors need a firm grasp of how CSS handles document structure, how one writes rules that behave as expected, and most of all, what the "Cascading" part of the name really means.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Selectors and Structure
The life of a web designer can be pretty rough at times. How many times have you slaved over a new design, guided it through 17 committees and 4 major revisions, and finally come up with something that everyone seems to like, when a vice-presidential voice suddenly says, "I'm concerned about the shade of green we're using for our headings. Could we see some versions of the site using a few lighter shades, and maybe a couple of darker shades as well?"
Well, now you're faced with the necessity of scheduling another meeting so you can go back to your computer and produce new versions of the design, replacing all of your <FONT COLOR="green"> tags with new ones that have different shades of green. Meanwhile, all the other administrators have started to think of their own ways to nitpick the design to death. Maybe the headings should be dark blue instead of green, or perhaps the sidebar's background is the wrong color, or maybe the company logo ought to be used for list-item bullets instead of those little black dots that everyone else uses.
So, at the next design meeting, after everyone's agreed that such-and-so shade of green is a good one, all these new revision ideas start popping up, and all the administrators are nodding gravely and saying, why yes, maybe we should see a design which uses shades of red, not green. The downward spiral has begun.
Even if you're lucky enough to work in a place where you don't have to tolerate such nonsense, you probably pose similar questions to yourself while you're working on your design. Does the particular blue you're using for your sidebar's background contrast enough with your yellow links? Would the headings all look better if they were red instead of green? What if the paragraphs were in one font and the headings in another? The only way to find out is to fiddle with FONT tags and BGCOLOR attributes. That can take forever if you have a lot of documents, or a really complicated design, and if you suddenly head in a different direction, you can spend almost as much time cleaning up the residue of your old assumptions as you do on actual creative design work.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic Rules
Central to CSS is the ability to apply certain rules to the same types of elements in a document, which can drastically reduce the amount of work an author has to undertake. For example, let's say that you wish to make the text of all H2 elements appear gray. Using straight HTML, you'd have to do this by inserting <FONT color="gray">...</FONT> tags in all your H2 elements, something like this:
<H2><FONT COLOR="gray">This is H2 text</FONT></H2>
If you have a document with a lot of H2 elements, this can become very tedious to type. If you later decide that you want to change all the H2s to be green instead of gray, then the task becomes even worse because you have to find all of those H2s and change the value of each and every FONT tag to be gray.
In CSS, you can avoid all that hassle, and still get the effects you want in a way that makes them easy to change. In the document's style sheet, you need only define the following to get the same result:
H2 {color: gray;}
Altogether, this is known as a rule. This single rule is enough to cause all H2 elements to be colored gray. If you want to change this to another color, then the alteration of this single rule will affect all H2s in the document:
H2 {color: silver;}
In order to understand this in more detail, let's break down the structure of a rule.
Each rule has two parts, the selector and the declaration . At a finer level, each declaration is actually a combination of properties and values. Every style sheet is made up of a series of rules, but rules do not always appear in style sheets.
First, however, let's break down our example rule into its various parts, as shown in Figure 2-1.
Figure 2-1: The structure of a rule
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Grouping
So far, things have been pretty simple—as long as you only want to apply a single style to a single selector, that is. No doubt you'll want to go further than that, though: sometimes you'll want the same style to apply to multiple elements, which means you'll want to use more than one selector, and other times, you'll want to apply more than one style to an element or group of elements.
Let's say you have a document in which both H2 elements and paragraphs should have gray text. The easiest way to accomplish this is to use the following.
H2, P {color: gray;}
By placing both the H2 and P selectors on the left side of the rule and separating them with a comma, we've defined a rule where the style on the right (color: gray;) is applied to both selectors. The comma tells the browser that there are two different selectors involved in the rule. Leaving out the comma would give the rule a completely different meaning, which we'll explore later, in Section 2.5.1.
It is possible to group any number of selectors together. If you wanted to make sure that every element in your document had a color of gray, you might use the following rule:
BODY, TABLE, TH, TD, H1, H2, H3, H4, P, PRE, STRONG, EM, B, I {color: gray;}
As you can tell, grouping allows an author to drastically compact certain types of style assignments which might otherwise result in a very long style sheet. The following two alternatives will have exactly the same result, but it's pretty obvious which one is easier to type:
H1 {color: purple;}
H2 {color: purple;}
H3 {color: purple;}
H4 {color: purple;}
H5 {color: purple;}
H6 {color: purple;}
or:
H1, H2, H3, H4, H5, H6 {color: purple;}
Grouping can make for some interesting choices. For example, all of the style sheets in the following example are equivalent—each merely shows a different way of grouping both selectors and declarations—and any of them will yield the result shown in Figure 2-3:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Class and ID Selectors
So far, we've been grouping selectors and declarations together in a variety of ways, but for all that, the selectors we've been using are very simple ones. They only refer to document elements, and while that's often just what you need, there are times when something a little more specialized is required.
In addition to raw document elements, there are two other kinds of selectors: class and ID selectors, which allow the assignment of styles in a way that is independent of document elements. These selectors can be used on their own or in conjunction with element selectors. However, they only work if you've marked up your document appropriately, so using them generally involves a little forethought and planning.
Of course, you probably want to know why you should go to the effort. What will it get you? Let's consider a document about the handling of plutonium, in which there are various warnings on things to do (or not do) while working with such a dangerous substance. You want to make each warning use boldface text so that it will stand out from everything else.
However, you don't know what kind of elements these warnings will be. Sometimes there will be a whole paragraph of warning text, but other times there might be a single warning list item out of a lengthy list, or just a given section of a paragraph. In any case, you can't define a rule using simple selectors of any kind. If you did this:
P {font-weight: bold;}
then all paragraphs will be bold, not just those that contain warnings. You need a way to only select the paragraphs that are warnings, or more precisely, a way to select only those elements that are warnings.
Another scenario involves ways of styling different kinds of links. You might wish to set a different color for links that point to pages not found on your site. Once more, you can't just write:
A {color: maroon;}
because that will select all anchors, regardless of whether they point to pages on your site or off it.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Pseudo-Classes and Pseudo-Elements
Even more interesting, at least in terms of syntax, are the pseudo-class and pseudo-element selectors. These allow the author to assign styles to structures that don't necessarily exist in the document, or to things that are inferred by the state of certain elements, or even the state of the document itself. In other words, the styles are applied to pieces of a document based on something other than the structure of the document, and in a way that cannot be precisely deduced simply by studying the document's markup.
This may sound like we're applying styles at random. Not at all! Instead, the styles are applied based on somewhat ephemeral conditions that can't be predicted in advance. Nonetheless, the circumstances under which the styles will appear are well-defined. This is sort of like saying, "During a sporting event, whenever the home team scores, the crowd will cheer." You don't know exactly when during a game this will happen, but when the right conditions occur, the crowd will do just as predicted. The fact that you can't predict the exact second (or inning, or quarter) in which this will happen doesn't make the behavior any less expected whenever the home team does score.
First we'll look at pseudo-class selectors, since they're better supported by browsers and therefore more widely used. Let's use an example to see how they work; this will take a minute before I reach the actual point, so bear with me.
Consider the anchor, which is used to set up a link from one document to another. Anchors are always anchors, of course, but some anchors refer to pages that have already been visited, while others refer to pages that haven't been visited yet. You can't tell which are which by simply looking at the HTML markup, because in the markup, all anchors look the same. Only by comparing the links in a document to the user's browser history is it possible to tell which links have been visited and which have not. So, in a certain sense, there are two basic types of anchors: visited and unvisited. In fact, these types are known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Structure
As I've mentioned before, CSS is powerful because of the way in which it uses the structure of HTML documents to determine which styles should be applied in what ways. That's really only a part of the story, though, since it implies that the only way CSS uses document structure is to determine which rules apply to which elements.
The truth is that structure plays a much bigger role in the way styles are applied to a document. In order to understand this role, we need to understand how documents are structured. Take the "tree" view in Figure 2-18 of the simple HTML document listed here:
<HTML>
<HEAD>
<BASE HREF="http://www.meerkat.web/">
<TITLE>Meerkat Central</TITLE>
</HEAD>
<BODY>
<H1>Meerkat <EM>Central</EM></H1>
<P>
Welcome to Meerkat <EM>Central</EM>, the <STRONG>best meerkat web site 
on <A HREF="inet.html">the <EM>entire</EM> Internet</A></STRONG>!</P>
<UL>
<LI>We offer:
<UL>
<LI><STRONG>Detailed information</STRONG> on how to adopt a meerkat</LI>
<LI>Tips for living with a meerkat</LI>
<LI><EM>Fun</EM> things to do with a meerkat, including:
<UL>
<LI>Playing fetch</LI>
<LI>Digging for food</LI>
<LI>Hide and seek</LI>
</UL>
</LI>
</UL>
<LI>...and so much more!</LI>
</UL>
<P>
Questions? <A HREF="mail to:suricate@meerkat.web">Contact us!</A>
</P>
</BODY>
</HTML>
Much of the power of CSS is based on the parent-child relationship of elements. HTML documents, and indeed most structured documents of any kind, are based on a hierarchy of elements, which is visible in the "tree" view of the document in Figure 2-18. In this hierarchy, each element fits somewhere into the overall structure of the document, and every element is either the parent or child of another element, and often both.
Figure 2-18: The "tree view" of a simple HTML document
An element is said to be the parent of another element if it encloses the other element. For example, in Figure 2-18, the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Inheritance
Viewing a document as a tree is very important for one other reason: a key feature of CSS is inheritance , which relies on the ancestor-descendant relationship to operate. Inheritance is simply the mechanism by which styles are applied not only to a specified element, but also to its descendants. If a color is applied to an H1 element, for example, then that color is applied to all text in the H1, even the text enclosed within child elements of that H1:
H1 {color: gray;}

<H1>Meerkat <EM>Central</EM></H1>
As shown in Figure 2-23, both the ordinary H1 text and the EM text are colored gray because the value of color inherits into the EM element. This is very likely what the author intended, which is why inheritance is a part of CSS.
Figure 2-23: Inheritance of styles
The alternative would be a hypothetical situation where inheritance does not operate; in that case, the EM text would be black, not gray.
Another good example of how inheritance works is with unordered lists. Let's say we apply a style of color: gray for UL elements. What we expect is that a style that is applied to a UL will be applied to its list items as well, and to any content of those list items. Thanks to inheritance, that's exactly what does happen, as Figure 2-24 demonstrates:
UL {color: gray;}
Figure 2-24: Inheritance of styles
Inheritance is one of those things about CSS that are so basic that you almost never think about them unless you have to—rather like the way we tend to take the convenience of the highway system for granted until part of it is closed or otherwise rendered difficult to use. However, there are a few things to keep in mind about inheritance.
As with any great thing, there are a few blemishes if you look closely enough. First off, some properties are not inherited. This may be for any number of reasons, but they generally have to do with simple common sense. For example, the property
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Specificity
Given the existence of inheritance, one might well wonder what happens in a circumstance such as this:
.grape {color: purple;}
H1 {color: red;}

<H1 CLASS="grape">Meerkat <EM>Central</EM></H1>
Since the selectors H1 and .grape can both match the H1 element shown, which one wins? As it happens, .grape is the correct answer, and so the H1 element will be colored purple. This happens because of the specificity of the two rules, and the rules CSS has to deal with such situations.
Specificity describes the relative weights of various rules. According to the specification, a simple selector (e.g., H1) has a specificity of 1, class selectors have a specificity of 10, and ID selectors a specificity of 100. Thus the following rules would have the noted specificity:
H1 {color: red;}                    /* specificity = 1 */
P EM {color: purple;}               /* specificity = 2 */
.grape {color: purple;}             /* specificity = 10 */
P.bright {color: yellow;}           /* specificity = 11 */
P.bright EM.dark {color: brown;}    /* specificity = 22 */
#id216 {color: blue;}               /* specificity = 100 */
Thus, the rule for #id216 has a much higher specificity, and therefore more weight, than any of the others listed. In cases where more than one rule can apply to an element, the styles with the higher weight win out.
Within the framework of specificity, inherited values have, effectively, a specificity of 0. This means that any explicitly declared rule will override an inherited style. Therefore, no matter how much weight a rule might have, it is only inherited if no other rule can be applied to the inheriting element.
For example, consider the following:
BODY {background: black;}
LI {color: gray;}
UL.vital {color: white;}
You would likely expect that all list items would be gray except for those which are found in lists with a class of vital, in which case they'll be white. However, as Figure 2-26 demonstrates, this is not the case.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Cascade
Through all this, we've skirted one rather important issue: what happens when there are two rules of equal specificity that apply to the same element? How does the browser resolve the conflict?
For example, let's say we have the following rules:
H1 {color: red;}
H1 {color: blue;}
So which one wins? Both have a specificity of 1, so they have equal weight and should both apply. That simply can't be the case, though, because the element can't be both red and blue. It has to be one or the other. But which?
This is where the name "Cascading Style Sheets" finally makes some sense. CSS is based on a method of causing styles to cascade together—a method that is made possible by the rules of inheritance and specificity, as it happens. The cascade rules are simple enough:
  1. Find all declarations that contain a selector that matches a given element.
  2. Sort by explicit weight all declarations applying to given element. Those rules marked !important are given higher weight than those that are not. Also sort by origin all declarations applying to a given element. There are three origins: author, reader, and user agent. Under normal circumstances, the author's styles win out over the reader's styles. !important author styles win out over important reader styles in CSS1, but in CSS2, !important reader styles are stronger than any other styles. Either author or reader styles will override user agent styles.
  3. Sort by specificity all declarations applying to a given element. Those elements with a higher specificity have more weight than those with lower specificity.
  4. Sort by order all declarations applying to a given element. The later a declaration appears in the style sheet or document, the more weight it is given. Declarations that appear in an imported style sheet are considered to come before all declarations within the style sheet that imports them, and declarations within
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Classification of Elements
As we have already discussed, elements in a document occur in a sort of hierarchy. At the most basic level, block-level elements contain other block-level elements, inline elements, and replaced elements. A part of this hierarchy scheme depends on the relationships between these types of elements; for example, while inline elements can be children of block-level elements, the reverse is not true.
In CSS, elements are grouped into three types:
Block-level elements
Elements such as paragraphs, headings, lists, tables, DIVs, and BODY. Replaced elements, such as images and form inputs, can be block-level elements but usually are not. Each block-level element is displayed on a line by itself, so to speak, beginning on a new line and forcing any element after it to do the same. Block-level elements can only be children of other block-level elements, and then only in certain circumstances.
Inline elements
Elements such as A, EM , SPAN, and most replaced elements, such as images and form inputs. They do not force anything to start on a new line, not even themselves, and can be the children of any other element.
List-item elements
Elements that in HTML pretty much include only the LI element. These are specially defined to have presentation aspects such as a "marker" (a bullet, letter, or number) and a certain sense of ordering, if such an element appears within an ordered list of some kind. Thus, list items within such a list can be automatically numbered, based on their context within the document.
These terms are, as it happens, the basic three of the four values for the property display.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
By using selectors based on the document's language, authors can create CSS rules that apply to a large number of similar elements just as easily as they can construct rules that apply in very narrow circumstances. The ability to group together both selectors and declarations keeps style sheets compact and flexible, which incidentally leads to smaller file sizes and faster download times. Thanks to inheritance and the cascade, authors are able to create sets of interlocking rules which, taken together, result in sophisticated document styles. This is all thanks to the fact that CSS is very deeply bound to the structure of documents, and that it uses this structure to determine how rules are applied, which rules should apply, and what elements should assume styles from their ancestors.
Selectors are the one thing that user agents almost have to get right, because the inability to correctly interpret selectors pretty much prevents a user agent from using CSS. However, the cascade and inheritance are different stories, and there have been some flaws in how they're implemented. Navigator 4.x, for example, has a rough time with inheritance into tables, as well as other structures such as lists. You can clear up many of these problems by using very strictly correct HTML, but not all of them.
There are many CSS rules describing lengths, colors, or other things that can be expressed using specific units and values—and this is the subject (and title) of the next chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Units and Values
In this chapter, we study the basis for almost everything that can be done in CSS: the units that affect the color used or the distance set for a whole host of properties. Without units, it wouldn't be possible to declare that a paragraph should be purple, or that an image should have ten pixels of blank space around it, or that a heading should be a certain size. By understanding the concepts put forth here, you'll be able to learn and use the rest of CSS much more quickly.
However, that's the good news. The bad news is that this chapter will contain a good many caveats, warnings, and discussions of browser bugs and inconsistencies between operating systems. Remember, though, that CSS is not supposed to be a totally precise layout language—and besides, many of the issues discussed in the chapter are not the fault of CSS but are more fundamental issues that you'll encounter no matter what you try to do with a computer. So, once you've finished this chapter, you will have a grasp not only of how CSS units work, but perhaps also of a few basic issues that you previously were unaware of.
Above all, though, regardless of how bleak things may seem, keep going! Your perseverance will be rewarded.
Of course, the one thing that almost every beginning web author wants to know is, "How do I set colors on my web page?" Under HTML, there were two choices: use one of a small number of colors with names, like red or purple, or employ a vaguely cryptic method using hexadecimal codes. Well, both of those methods for describing colors can be found in CSS, as well as some other methods that are only moderately complex.
Assuming that you're happy with picking from a small, basic set of colors, then the easiest method is to simply use the name of the color you want. These are referred to, unsurprisingly enough, as named colors.
Contrary to what some browser companies might have you believe, you are limited in the range of named colors available. For example, setting a color to "mother-of-pearl" isn't going to work, because it isn't a defined color. (Well, not yet, at any rate.) Technically speaking, there are
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Colors
Of course, the one thing that almost every beginning web author wants to know is, "How do I set colors on my web page?" Under HTML, there were two choices: use one of a small number of colors with names, like red or purple, or employ a vaguely cryptic method using hexadecimal codes. Well, both of those methods for describing colors can be found in CSS, as well as some other methods that are only moderately complex.
Assuming that you're happy with picking from a small, basic set of colors, then the easiest method is to simply use the name of the color you want. These are referred to, unsurprisingly enough, as named colors.
Contrary to what some browser companies might have you believe, you are limited in the range of named colors available. For example, setting a color to "mother-of-pearl" isn't going to work, because it isn't a defined color. (Well, not yet, at any rate.) Technically speaking, there are no defined colors, but there are 16 colors that are suggested by the specification and that all major browsers recognize:
aqua
gray
navy
silver
black
green
olive
teal
blue
lime
purple
white
fuchsia
maroon
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Length Units
A lot of CSS properties, such as margins, depend on length measurements in order to properly display various page elements. It probably comes as no surprise to you, then, that there are a number of ways to measure length in CSS.
All length units can be expressed as either positive or negative numbers, followed by a label—although some properties will only accept positive numbers. They are also real numbers; that is, numbers with decimal fractions, such as 10.5 or 4.561. All length units are followed by a two-letter abbreviation that represents the actual unit of length being specified, such as in (inches), or pt (points). The only exception to this rule is a length of 0 (zero), which need not always be followed by a unit.
These length units are divided into two types: absolute units and relative units.
No vodka jokes, please. We start with absolute units because they're easiest to understand, despite the fact that they're almost unusable in web design. The five types of absolute units are as follows:
Inches (in)
As you might expect, the inches one finds on a ruler in America. The fact that this unit is even in the specification, given that almost the entire world uses the metric system, is an interesting insight into the pervasiveness of American interests on the Internet—but let's not get into virtual sociopolitical theory right now.
Centimeters ( cm)
The centimeters that one finds on rulers the world over. There are 2.54 cm to an inch, and one centimeter equals 0.394 inches.
Millimeters ( mm)
You guessed it. For those Americans who are metric-challenged, there are 10 millimeters to a centimeter, so you get 25.4 mm to an inch, and 1 millimeter equals 0.0394 inches.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Percentage Values
Compared to length units, percentage units are almost laughably simple. They're pretty much exactly what you'd expect—a positive or negative number, followed by a percent sign (%). For example:
H1 {font-size: 18pt;}
H1.tall {line-height: 150%;}
This sets the line-height of all H1 elements with a class of tall to be half again as large as normal, as we see in Figure 3-8.
Figure 3-8: Line height of 100% (top) and 150% (bottom)
Percentage values are always computed relative to another value—usually a length unit. In this case, the line-height is exactly 27 points (18pt times 1.5). This is the same as setting the line-height to 1.5em , although neither method is particularly recommended over the other.
Percentages can, in general, be either positive or negative. However, there are properties that accept percentage values, but will not permit negative values (of any kind, including percentages). These will be mentioned as the properties are covered in subsequent chapters.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
URLs
If you've written web pages, then you're familiar with URLs. URLs aren't often used in style sheets, but if you do need to refer to one—as in the @import statement, which is used when importing an external style sheet—then the general format is:
url(http://server/pathname)
This example defines an absolute URL. By absolute, we mean a URL that will work no matter what page it's found in, because it defines an absolute location in web space. Let's say that we have a server called www.waffles.org. On that server, there is a directory called pix, and in this directory is an image waffle22.gif. In this case, the absolute URL of that image would be http://www.waffles.org/pix/waffle22.gif. This URL is valid no matter where it is found, whether the page is on the server www.waffles.org or web.pancakes.com.
The other type of URL is a relative URL, so named because this type of URL specifies a location that is relative to the document that uses it. If you're referring to a relative location, such as a file in the same directory as your web page, then the general format is:
url(pathname)
This only works if the image is on the same server as the page that contains the URL. For argument's sake, we'll assume that we have a web page located at http://www.waffles.org/syrup.html and that we want the image waffle.gif to appear on this page. In that case, the relative URL could be pix/waffle22.gif.
This works because the web browser knows that it should take the same place it found the web document and add the relative URL to it. In this case, the server name http://www.waffles.org/ added to the pathname pix/waffles22.gif equals http://www.waffles.org/pix/waffle22.gif.
Here are two more examples:
@import url(http://css1.style.org/example.css);

BODY {background-image: url(hatch.gif);}
It doesn't really matter whether you use absolute or relative URLs, so long as they define valid locations. You can use whichever is easier for you and your project.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
CSS2 Units
In addition to what we've covered, CSS2 adds a small number of new units, almost all of which are concerned with aural style sheets (employed by those browsers that are capable of speech). We'll briefly cover them here:
Angle values
Used to define the position from which a given sound should seem to originate. There are three type of angles: degrees (deg ), grads (grad ), and radians (rad ). For example, a right angle could be declared as 90deg, 100grad , or 1.57rad ; in each case, the values are translated into degrees in the range 0 through 360. This is also true of negative values, which are allowed. The measure -90deg is the same as 270deg.
Time values
Used to specify delays between speaking elements, these values can be expressed as either milliseconds (ms) or seconds (s). Thus, 100ms and 0.1s are equivalent. Time values may not be negative.
Frequency values
Used to declare a given frequency for the sounds that speaking browsers can produce. Frequency values can be expressed as hertz (Hz) or megahertz (mHz) and cannot be negative. The values labels are case-insensitive, so 10mHz and 10mhz are equivalent.
In addition to these values, there is also an old friend with a new name. A URI is a Uniform Resource Identifier, which is sort of another name for a Uniform Resource Locator (URL). The difference is, for now, mostly semantic, but many authors are beginning to adopt the convention of referring to online addresses as URIs, not URLs. The specification still requires that URIs be declared with the form url(...), though, so it's hard to know exactly what the point was of including a section in CSS2 about how CSS2 uses URIs instead of URLs.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
Units and values cover a wide spectrum of areas, from length units to color units to the location of files (such as images). For the most part, units are the one area that user agents get almost totally correct; it's those few little bugs and quirks that get you, though. Interpreting relative URLs incorrectly, for example, has bedeviled many authors, and leads to an over-reliance on absolute URLs. Colors are another area where user agents almost always do well, except for a few little quirks here and there. The vagaries of length units, however, far from being bugs, are an interesting problem for any author to tackle.
These units all have their advantages and drawbacks, depending on the circumstance in which they're used. We've already seen some of these, and the nuances of such circumstances will be discussed in the rest of the book, beginning with the CSS properties that describe ways to alter the way text is displayed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Text Properties
While your web design efforts may be largely focused on picking the right colors and getting the coolest look for your pages, when it comes right down to it, you'll probably spend most of your time worrying about where text will go and how it will look. This concern gave rise to HTML tags such as <FONT> and <CENTER>, which give you some measure of control over the appearance and placement of text.
Because of this fact, much of CSS is concerned with properties that affect text in one way or another. In CSS1, the properties are split up into two sections: "Text Properties" and "Font Properties." This chapter is devoted to explaining the former. We'll tackle fonts in Chapter 5—they're quite complicated in their own way and so deserve a chapter all their own.
You may well wonder what the difference is between text and fonts. Simply put, text is the content. The font used to display it is just one more way of altering the appearance of the text. Before we get into fonts, though, there are some simpler ways to affect the appearance of your text. Besides, some of the things we discuss here will be important when we discuss the font properties, so it makes more sense to discuss the text properties first.
With the text properties, you can affect the position of text in relation to the rest of the line, and do things like superscripting, underlining, and changing the capitalization. You can even simulate, to a limited degree, the use of the Tab key on a typewriter.
It's best to start with a discussion of how you can affect the horizontal positioning of text within a line. This is not the same as actual positioning, which is done with respect to the page itself. Think of these properties as ways to affect how the lines of text are laid out, as you might do when creating a newsletter or writing a report.

Section 4.1.1.1: Indenting text

One of the most sought-after effects in text formatting on the Web is the ability to indent the first line of a paragraph. (Close behind that is the desire to eliminate the "blank line" between paragraphs, which is discussed in Chapter 7). Some sites solve this by placing a small transparent image before the first letter in a paragraph, thus shoving the text over, and others use the utterly nonstandard
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Manipulating Text
You may well wonder what the difference is between text and fonts. Simply put, text is the content. The font used to display it is just one more way of altering the appearance of the text. Before we get into fonts, though, there are some simpler ways to affect the appearance of your text. Besides, some of the things we discuss here will be important when we discuss the font properties, so it makes more sense to discuss the text properties first.
With the text properties, you can affect the position of text in relation to the rest of the line, and do things like superscripting, underlining, and changing the capitalization. You can even simulate, to a limited degree, the use of the Tab key on a typewriter.
It's best to start with a discussion of how you can affect the horizontal positioning of text within a line. This is not the same as actual positioning, which is done with respect to the page itself. Think of these properties as ways to affect how the lines of text are laid out, as you might do when creating a newsletter or writing a report.

Section 4.1.1.1: Indenting text

One of the most sought-after effects in text formatting on the Web is the ability to indent the first line of a paragraph. (Close behind that is the desire to eliminate the "blank line" between paragraphs, which is discussed in Chapter 7). Some sites solve this by placing a small transparent image before the first letter in a paragraph, thus shoving the text over, and others use the utterly nonstandard SPACER tag to get a similar effect. There is a better way, thanks to CSS.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
Even without trying to alter the font in use, there are many ways to change the appearance of text. There are classic effects such as underlining, of course, but CSS also gives us the ability to draw lines over text or through it, change the amount of space between words and letters, indent the first line of a paragraph (or other block-level element), align text to the left or right, and much more. You can even alter the amount of space between lines of text, although this operation is unexpectedly complicated and covered in detail in Chapter 8.
These behaviors are all relatively well supported, or else not supported at all. Full justification of text is one of the big ones that is not well supported, and most user agents released during the twentieth century exhibited bugs in the text decoration and vertical alignment, as well as line height calculations. On the other hand, word and letterspacing almost always work correctly when they're supported, and text indentation has experienced only a few very small bugs. The same is true of the ability to alter capitalization, which is usually supported correctly.
Of course, the other thing authors generally want to do with text is change which font is being used, as well as change its size, weight, and other aspects of the font. We'll see how this happens in the next chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Fonts
As the authors of the specification clearly recognized, font selection will be a popular feature of CSS. After all, how many pages are littered with dozens, or even hundreds, of <FONT face="..."> tags? In fact, the beginning of the "Font Properties" section of CSS1 begins with the sentence, "Setting font properties will be among the most common uses of style sheets."
The truth is that, for now, there isn't a way to ensure consistent font use on the Web, because there isn't a uniform way of describing fonts and variants of fonts. For example, the fonts Times, Times New Roman, and TimesNR may be similar or the same, but how would a user agent know that? An author might specify TimesNR in a document, but what happens when a user without that particular font installed views the document? Even if Times New Roman is installed, the user agent cannot know that the two are effectively interchangeable. And if you're hoping to force a certain font on a reader, forget it. Although CSS2 has facilities for downloadable fonts, these are not well implemented, and a reader could always refuse to download fonts for performance reasons. CSS does not provide ultimate control over fonts, any more than does a word processor: when a Microsoft Office document you have created