Style Properties

Style Properties

At the heart of the CSS2 standard are the many properties that let you control how the styles-conscious browser presents your documents to the user. The standard collects these properties into six groups: fonts, colors and backgrounds, text, boxes and layout, lists, and tag classification. We'll stick with that taxonomy and preface the whole shebang with a discussion of property values and inheritance before diving into the properties themselves.

You'll find a summary of the style properties in Appendix C.

Property Values

Most properties set a value to some characteristic of your document for rendering by the browserthe size of the characters in a font or the color of level-2 headers, for example. As we discussed earlier, when describing the syntax of styles, you give value to a CSS2 property by following the property's keyword with a colon (:) and one or more space- or comma-separated numbers or value-related keywords. For example:

font-family: Helvetica, Univers, sans-serif

color and font-family are the properties in these two style examples; blue and the various comma-separated font names are their values, respectively.

There are eight kinds of property values: keywords, length values, percentage values, URLs, colors, angles, time, and frequencies.

Keyword property values

A property may have a keyword value that expresses action or dimension. For instance, the effects of underline and line-through are obvious property values. And you express property dimensions with such keywords as small and xx-large. Some keywords are even relational: bolder, for instance, is an acceptable value for the font-weight property. Keyword values are not case sensitive: Underline, UNDERLINE, and underline are all acceptable keyword values.

Length property values

So-called length values (a term taken from the CSS2 standard) explicitly set the size of a property. They are numbers, some with decimals, too. Length values may have a leading + or - sign to indicate that the value is to be added to or subtracted from the current value of the property. Length values must be followed immediately by a two-letter unit abbreviation, with no intervening spaces.

There are three kinds of length-value units: relative, pixels, and absolute. Relative units specify a size that is relative to the size of some other property of the content. Currently, there are only two relative units: em, which is the width of the lowercase letter "m" in the current font; and x-height, abbreviated ex, which is the height of the letter "x" in the current font.

Pixels are the tiny dots of colored light that make up the onscreen text and images on a computer monitor or TV image. The pixels unit, abbreviated px, is equal to the minute size of 1 pixel, so you may express the size of some properties by how many pixels across or down they run.

Absolute property value units are more familiar to us all. They include inches (in), centimeters (cm), millimeters (mm), points (pt; 1/72 of an inch), and picas (pc; 12 points).

All of the following are valid length values, although the current styles-conscious browsers do not recognize all units:


Percentage property values

Similar to the relative length property value type, a percentage value describes a proportion relative to some other aspect of the content. It has an optional sign, meaning it may be added to or subtracted from the current value for that property, and optional decimal portion to its numeric value. Percentage values have the percent sign (%) suffix. For example:

line-height: 120%

computes the separation between lines to be 120 percent of the current line height (usually relative to the text font height). Note that this value is not dynamic: changes made to the font height after the rule has been processed by the browser do not affect the computed line height.

URL property values

Some properties also accept, if not expect, a URL value. The syntax for a CSS2 URL property value is different from that in HTML/XHTML:


With CSS2 properties, the keyword url is required, as are the opening and closing parentheses. Do not leave any spaces between url and the opening parenthesis. The url value may contain either an absolute or a relative URL. However, the URL is relative to the stylesheet's URL, not necessarily the document's base URL. This means that if you use a url value in a document-level or inline style, the URL is relative to the HTML document containing the style document. Otherwise, the URL is relative to the @imported or <link>ed external stylesheet's URL.

Color property values

Color values specify colors in a property (surprised?). You can specify a color as a color name or a hexadecimal RGB triple, as for common HTML/XHTML attributes, or as a decimal RGB triple unique to style properties. Both color names and hexadecimal RGB triple notation are described in Appendix G.

With CSS2, too, you may assign just one hexadecimal digit instead of two to the red, green, and blue (RGB) components of a color. That digit is simply doubled to create a conventional six-digit triple. Thus, the color #78C is equivalent to #7788CC. In general, three-digit color values are handy only for simple colors.

The decimal RGB triple notation is unique:

rgb(red, green, blue)

The red, green, and blue intensity values are decimal integers in the range 0 to 255, or integer percentages. As with a url value, do not leave any spaces between rgb and the opening parenthesis.

For example, in decimal RGB convention, the color white is rgb(255, 255, 255) or rgb(100%, 100%, 100%), and a medium yellow is rgb(127, 127, 0) or rgb(50%, 50%, 0%).

Angle, time, and frequency property values

A few properties require a value that expresses an angle, such as the heading of a compass. These properties take a numeric value followed by the units deg (degrees), grad (gradations), or rad (radians). Similarly, express time values as numbers followed by either ms (milliseconds) or s (seconds) units.

Finally, frequency values are numbers followed by Hz (hertz) or kHz (1 kilohertz = 1000 Hz). Interestingly, there is no corresponding MHz or GHz units, because frequencies in CSS2 refer to audio, not TV, FM radio, Bluetooth wireless networking, or other electromagnetic waves.

Property Inheritance

In lieu of a specific rule for a particular element, properties and their values for tags within tags are inherited from the parent tag. Thus, setting a property for the <body> tag effectively applies that property to every tag in the body of your document, except for those that specifically override it. So, to make all the text in your document blue, you need only write:

body {color: blue}

instead of creating a rule for every tag you use in your document.

This inheritance extends to any level. If you later created a <div> tag with text styled by a different color, the styles-conscious browser would display all the text contents of that <div> tag and all its enclosed tags in that new color. When the <div> tag ends, the color reverts to that of the containing <body> tag.

In many of the following property descriptions, we refer to the tag containing the current tag as the parent element of that tag.

Font Properties

The loudest complaint that we hear about HTML and its progeny, XHTML, is that they lack font styles and characteristics that even the simplest of text editors implement. The various <font> attributes address part of the problem, but they are tedious to use, because each text font change requires a different <font> tag.

Stylesheets simplify all that, of course. The CSS2 standard provides seven font properties that modify the appearance of text contained within the affected tag: font-family, font-size, font-size-adjust, font-style, font-variant, font-stretch, and font-weight. In addition, there is a universal font property in which you can declare all the font values.

Please be aware that stylesheets cannot overcome limitations of the user's display/document-rendering system, and the browser cannot conjure effects if the fonts it uses do not provide the means.

The font-family property

The font-family property accepts a comma-separated list of font names. The browser uses the first font named in the list that also is installed and available for display on the client machine for text display.

Font-name values are for specific font styles, such as Helvetica and Courier, or for a generic font style, as defined by the CSS2 standard: serif, sans-serif, cursive, fantasy, and monospace. The browser defines which font it actually uses for each generic font. For instance, Courier is the most popular choice for a monospaced font.

Because fonts vary wildly among browsers, you should usually provide several choices when specifying a font style, ending with a suitable generic font. For example:

h1 {font-family: Helvetica, Univers, sans-serif}

causes the browser to look for and use Helvetica, and then Univers. If neither font is available for the client display, the browser uses the generic sans-serif typeface.

Enclose font names that contain spacesNew Century Schoolbook, for examplein quotation marks. For instance:

p {font-family: Times, "New Century Schoolbook", Palatino, serif}

With inline styles, that extra set of double quotation marks causes problems. The solution is to use single quotation marks in an inline style:

<p style="font-family: Times, 'New Century Schoolbook', Palatino, serif">

In practice, you don't have to use quotation marks, because font-name values are comma separated, so the browser normally ignores the spaces. Hence, both of the following are legal:

p {font-family: Times, New Century Schoolbook, Palatino, serif}
<p style="font-family: Times, New Century Schoolbook, Palatino, serif">

Nonetheless, we recommend that you use quotation marks. It's a good habit to get into, and it makes things that much less ambiguous.

The font-size property

The font-size property lets you prescribe absolute or relative length values, percentages, and keywords to define the font size. For example:

p {font-size: 12pt}
p {font-size: 120%}
p {font-size: +2pt}
p {font-size: medium}
p {font-size: larger}

The first rule is probably the most used, because it is the most familiar: it sets the font size for text enclosed in your document's paragraph(s) to a specific number of points (12 in this example). The second example rule sets the font size to be 20 percent larger than the parent element's font size. The third increases the font's normal size by 2 points.

The fourth example selects a predefined font size set by the browser, identified by the medium keyword. Valid absolute-size keywords are xx-small, x-small, small, medium, large, x-large, and xx-large; these usually correspond to the seven font sizes used with the size attribute of the <font> tag.

The last font-size rule selects the next size larger than the font associated with the parent element. Thus, if the size were normally medium, it would be changed to large. You can also specify smaller, with the expected results.

None of the current browsers handles incremented or decremented font sizes correctly. Rather, they ignore the decrement sign and size altogether, and misinterpret the incremented size value as an absolute size. For instance, in the middle example in this section, the font size would end up as 2 points, not 2 points larger than the normal size.

The font-stretch property

In addition to different sizes, font families sometimes contain condensed and expanded versions, in which the characters are squeezed or stretched, respectively. Use the font-stretch property to choose more compressed or stretched-out characters from your font.

Use the property value of normal to select the normal-size version of the font. The relative values wider and narrower select the next-wider or next-narrower variant of the font's characters, respectively, but not wider or narrower than the most ("ultra") expanded or contracted one in the family.

The remaining font-stretch property values choose specific variants from the font family. Starting from the most condensed and ending with the most expanded, the values are ultra-condensed, extra-condensed, condensed, semi-condensed, semi-expanded, expanded, extra-expanded, and ultra-expanded.

The font-stretch property, of course, assumes that your display fonts support stretchable fonts. Even so, the currently popular browsers ignore this property.

The font-size-adjust property

Without too many details, the legibility and display size of a font depend principally on its aspect ratio: the ratio of its rendered size to its x-height, which is a measure of the font's lowercase glyph height. Fonts with aspect ratios approaching 1.0 tend to be more legible at smaller sizes than fonts with aspect ratios approaching 0.

Also, because of aspect ratios, the actual display size of one font may appear smaller or larger than another font at the same size. So, when one font is not available for rendering, the substituted font may distort the presentation.

The font-size-adjust property lets you readjust the substituted font's aspect ratio so that it better fits the display. Use the property value of none to ignore the aspect ratio. Otherwise, include your desired aspect ratio (a decimal value less than one), typically the aspect ratio for your first-choice display font. The styles-conscious browser computes and displays the substituted font at a size adjusted to your specified aspect ratio:

s = (n/a) * fs

where s is the new, computer font size for display of the substituted font, calculated as the font-size-adjust value n divided by the substituted font's aspect ratio a times the current font size fs.

For example, let's imagine that your first-choice font is Times New Roman, which has an aspect ratio of 0.45. If it's not available, the browser may then substitute Comic Sans MS, which has an aspect ratio of 0.54. So that the substitution maintains nearly equivalent sizing for the font displaysay, at an 18-px font sizewith the font-size-adjust property set to 0.45, the CSS2-compliant browser would display or print the text with the substituted Comic Sans MS font at the smaller size of (0.45/0.54 x 18 px) = 15 px.

Unfortunately, we can't show you how the popular browsers would do this because they don't support it.

The font-style property

Use the font-style property to slant text. The default style is normal and may be changed to italic or oblique. For example:

h2 {font-style: italic}

makes all level-2 header text italic. Netscape 4 supported only the italic value for font-style; all current browsers support both values, although it is usually difficult to distinguish italic from oblique.

The font-variant property

Use the font-variant property to display text in small capitals. The default value for this property is normal, indicating the conventional version of the font. Otherwise, give the property the value small-caps to select a version of the font in which the lowercase letters have been replaced with small capital letters.

All the current browsers support this property. Internet Explorer versions 4 and 5 incorrectly displayed small-caps as all uppercase letters.

The font-weight property

The font-weight property controls the weight or boldness of the lettering. The default value of this property is normal. You may specify bold to obtain a bold version of a font or use the relative bolder and lighter values to obtain a version of the font that is bolder or lighter than the parent element's font.

To specify varying levels of lightness or boldness, set the value to a multiple of 100, between the values 100 (lightest) and 900 (boldest). The value 400 is equal to the normal version of the font, and 700 is the same as specifying bold.

The current browsers fully support this property.

The font property

More often than not, you'll find yourself specifying more than one font-related property at a time for a tag's text content display. A complete font specification can get somewhat unwieldy. For example:

p {font-family: Times, Garamond, serif;
   font-weight: bold;
   font-size: 12pt;
   line-height: 14pt}

To mitigate this troublesome and potentially unreadable collection, use the comprehensive font property and group all the attributes into one set of declarations:

p {font: bold 12pt/14pt Times, Garamond, serif}

The grouping and ordering of font attributes is important within the font property. The font style, weight, and variant attributes must be specified first, followed by the font size and the line height separated by a slash character, and ending with the list of font families. Of all the properties, the size and family are required; the others may be omitted.

Here are a few more example font style rules:

em {font: italic 14pt Times}
h1 {font: 24pt/48pt sans-serif}
code {font: 12pt Courier, monospace}

The first example tells the styles-conscious browser to emphasize <em> text using a 14-point italic Times face. The second rule has <h1> text displayed in the boldest 24-point sans-serif font available, with an extra 24 points of space between the lines of text. Finally, text within a <code> tag is set in 12-point Courier or the browser-defined monospaced font.

We leave it to your imagination to conjure up examples of the abuses you could foster with font styles. Perhaps a recent issue of Wired magazine, notorious for avant-garde fonts and other print-related abuses, would be helpful in that regard.

Font Selection and Synthesis

The original CSS standard, CSS1, had a simplistic font-matching algorithm: if your specified font does not exist in the local client's font collection, substitute a generic font. Of course, the results are often less than pleasing to the eye and can wreak havoc with the display. Moreover, there are often more suitable font substitutes than generic ones. The CSS2 standard significantly extends the CSS1 font-matching model and includes a new at-rule that lets authors define, download, and use new fonts in their documents.

CSS2 font-matching steps

The CSS2 font-matching algorithm has four steps. The first step is simply to use the specified font when it is found on the user's machine; this could be one of several font families specified in the stylesheet rule, parsed in their order of appearance.

The second step, taken when none of the fonts specified in the rule exists on the user's machine, has the browser attempt to find a close match among similar local fonts. For example, a request for Helvetica might wind up using Arial, a similar sans-serif font.

The third step in the CSS2 font-matching algorithm has the browser try to synthesize a font, taking a local font and changing it to match the specified one. For example, a request for 72-point Helvetica might be satisfied by taking the local 12-point Arial font and scaling it up to match the desired size.

Failing all three previous steps, the browser may take a fourth step and download the desired font, provided the author has supplied suitable external font definitions. These external font definitions are created with the @font-face at-rule, whose general syntax is:

@font-face {
   descriptor : value;
   descriptor : value

Each @font-face at-rule defines a new font to the browser. Subsequent requests for fonts may be satisfied by these new fonts. The browser uses the various descriptor values to ensure that the font supplied matches the font requested.

Basic font descriptors

The basic font descriptors that you use in the @font-face at-rule correspond to the CSS2 font properties and accept the same values as those properties. Accordingly, use the font-family, font-style, font-variant, font-weight, font-stretch, and font-size descriptors and their associated values to define a new font to the browser. For example:

@font-face {
   font-family : "Kumquat Sans";
   font-style : normal, italic;
   src : url("")

defines a font named Kumquat Sans that is available for download from Within that downloadable font, both the normal and the italic versions of Kumquat Sans are available. Because we provide no other font descriptors, the browser assumes that all other font properties (weight, variant, etc.) can be satisfied within this font.

In general, omitting a font descriptor lets the browser match any value provided for that descriptor. By providing one or more values for a font descriptor, you are restricting the browser to match only those values in later font requests. Hence, you should be as specific as possible when defining a font this way, to better ensure that the browser makes good matches later. For example, if a font does not contain an italic version and you fail to tell the browser, it may use an incorrect font when attempting to fulfill a request for an italic style of that font.

The src descriptor

The src descriptor in the @font-face at-rule tells the browser where to retrieve the font. For downloadable fonts, the value of this descriptor is its document URL, expressed in CSS2 syntax with the url keyword. To reference locally installed fontsones stored on the user's machinewith src, use the keyword local rather than url and supply the local name of the font.

The src descriptor's value may also be a list of locations, separated by commas. In our previous example, we could have used:

src : url(""), local("Lucida Sans")

which asks the browser to download and use Kumquat Sans from and, if that fails, to look for a locally installed copy of Lucida Sans.

You can even provide hints to the browser. CSS2 is decidedly nonpartisan when it comes to the format of the font file. Recognizing that a number of different font formats exist, the standard lets you use any format you want, presuming that the browser can make sense of it. To provide a format hint, use the keyword format followed by one or more format names, such as:

src : url("") format("type-1"),
    local("Lucida Sans") format("truetype", "intellitype")

In this case, the external font is in Type 1 format, and the local flavors of Lucida Sans are available in both TrueType and Intellifont formats. Other recognized font formats include truedoc-pfr, opentype, embedded-opentype, truetype, truetype-gx, and speedo.

Advanced font descriptors

In addition to the standard font descriptors, CSS2 supports a number of more esoteric ones that further refine the defined font. Typical page designers do not have much need for these descriptors, but more discriminating typographers may find them useful.

The unicode-range descriptor accepts a comma-separated list of Unicode values, each beginning with U+ followed by a hexadecimal value. You can specify ranges of values by adding a dash and another hexadecimal value; the question mark matches any value in that position.

The purpose of the unicode-range descriptor is to define exactly which character glyphs are defined in the font. If characters used in your document are not available, the browser does not download and use the font. For example, a value of U+2A70 indicates that the font contains the glyph at that position in the font. Using U+2A7? represents characters in the range 2A70 to 2A7F, and U+2A70-2A9F defines a broader range. For the most part, this descriptor is used to restrict the use of special symbol fonts to just those symbols defined in the font.

The units-per-em descriptor accepts a single numeric value defining the size of the font's em area. This value is important if you specify the values of other descriptors using em units.

The panose-1 descriptor accepts exactly 10 integer values, separated by spaces, corresponding to the Panose-1 characterization of this font. Defining the actual Panose-1 values is well beyond the scope of this book; interested authors should refer to appropriate documentation for the Panose-1 system for more information.

The stemv and stemh descriptors define the thickness, in ems, of the vertical and horizontal strokes of the font. Similarly, the cap-height and x-height descriptors define the height of the upper- and lowercase glyphs in the font. Finally, the ascent and descent descriptors define the font's maximum height and depth. If you use any of these descriptors, you must also specify the units-per-em descriptor.

The slope descriptor defines the slope of the vertical stroke of the font. This is important for matching italic and oblique versions of a font.

The baseline, centerline, mathline, and topline descriptors define the conventional baseline, center baseline, mathematical baseline, and top baseline of the font. All accept a numeric value expressed in ems. All require that you specify the units-per-em descriptor, too.

The bbox descriptor accepts exactly two coordinate (X, Y) pairs, specifying the lower-left and upper-right corners of the font's bounding box. The bbox descriptor is important if the browser chooses to synthesize a font based on this font. By specifying the size of the bounding box, you ensure that the synthesized font occupies the same space as the desired one.

The widths descriptor accepts a comma-separated list of Unicode ranges, followed by space-separated values which define the widths of the characters in the indicated range. If you supply one value for a range, all the characters in that range have the same width. Multiple values are assigned to successive characters in a range. Like the bbox descriptor, the widths descriptor is used to ensure good fidelity between a synthesized font and its requested counterpart.

Finally, the optional definitions-src descriptor provides the URL of a file that contains all of the descriptors for a font. This is handy if you need to define a font in great detail. Instead of including the lengthy descriptors in each document or stylesheet that uses the font, you define the descriptors once in a separate file and reference that file using the definitions-src descriptor.

Color and Background Properties

Every element in your document has a foreground and a background color. In some cases, the background is not one color, but a colorful image. The color and background style properties control these colors and images.

The children of an HTML/XHTML element normally inherit the foreground color of their parent. For instance, if you make <body> text red, the styles-conscious browser also displays header and paragraph text in red.

Background properties behave differently, howeverthey are not inherited. Instead, each element has a default background that is transparent, allowing the parent's background to show through. Thus, setting the background image of the <body> tag does not cause that image to be reloaded for every element within the body tag. Instead, the browser loads the image once and displays it behind the rest of the document, serving as the background for all elements that do not themselves have an explicit background color or image.

All the current popular browsers support the following background and color properties.

The background-color property

The background-color property controls the (you guessed it!) background color of an element. Set it to a color value or to the keyword transparent (the default value). The effects should be obvious.

While you may have become accustomed to setting the background color of an entire document through the special attributes for the <body> tag, you can apply the background-color style property to any element. For example, to set the background color of one item in a bulleted list, you could use:

<li style="background-color: blue">

Similarly, you could give all the table header cells in a document a snapshot negative effect with:

th {background-color: black; color: white}

If you really want your emphasized text to stand out, paint its background red:

em {background-color: red}

The background-image property

The background-image property puts an image behind the contents of an element. Its value is either a URL or the keyword none (the default value).

As with background colors, you can place a background image behind the entire document or behind selected elements of a document. With this style property, effects such as placing an image behind a table or selected text are now simple:

<table style="background-image: url(backgrounds/woodgrain.gif)">
li.marble {background-image: url(backgrounds/marble.gif)}

The first example uses an inline style to place a wood grain finish behind a table. The second defines a list-item class that places a marble background behind <li> tags that use the class=marble attribute. For example, this XHTML snippet:

<h2>Here's what's for dinner tonight:</h2>
   <li class="marble">Liver with Onions</li>
   <li class="marble">Mashed Potatoes and Gravy</li>
   <li class="marble">Green Beans</li>
   <li class="marble">Choice of Milk, Tea, or Coffee</li>
<h2>And for dessert:</h2>
   <li>Creamed Quats in Milk (YUM! YUM!)</li>

produces a result like that in Figure.

Placing a background image behind an element

If the image is larger than the containing element, it is clipped to the area occupied by the element. If the image is smaller, it is repeated to tile the area occupied by the element, as dictated by the value of the background-repeat attribute.

You control the starting position of the image within the element with the background-position property. The background-attachment property manages the scrolling behavior of the image.

While it may seem that a background color and a background image are mutually exclusive, you should usually define a background color even if you are using a background image. That way, if the image is unavailablefor example, when the user doesn't automatically download imagesthe browser displays the background color instead. In addition, if the background image has transparent areas, the background color is used to fill in those areas.

The background-attachment property

If you specify a background image for an element, use the background-attachment property to control how that image is attached to the browser's display window. With the default value scroll, the browser moves the background image with the element as the user scrolls through the document. A value of fixed prevents the image from moving.

The background-position property

By default, the styles-conscious browser begins rendering a background image starting in the upper-left corner of the allotted display area. With the background-position property, you can offset the starting position of the background image by an absolute (length) or relative (percentage or keyword) offset. The resulting, potentially "cropped," image fills the area from that offset starting point.

You may specify one or two values for the background-position property. If you use a single value, it applies to both the vertical and horizontal positions. With two values, the first is the horizontal offset and the second is the vertical offset.

Length values (with their appropriate units; see section, earlier in this chapter) indicate an absolute distance from the upper-left corner of the element behind which you display the background image. Negative length values effectively crop the corresponding top and left sides of the image within the allotted viewport, just as an image that is too big for the browser's window gets cropped on the bottom and right sides.

For example:

table {background-image: url(backgrounds/marble.gif);
       background-position: 10px 20px}

offsets the marble background 10 pixels to the right and 20 pixels down from the upper-left corner of any <table> element in your document.

Percentage values are a bit trickier but somewhat easier to use. Measured from 0 percent to 100 percent from left to right and top to bottom, the center of the element's content display space is at 50%, 50%. Similarly, the position one-third of the way across the area and two-thirds of the way down is at 33%, 66%. So, to offset the background for our example dinner menu to the center of the element's content display space, we use:[*]

[*] Interestingly, this property worked as advertised with Internet Explorer versions 4 and 5 but is broken in version 6, as it is with other popular browsers: the offset works only if you set the background-repeat property.

background-position: 50%

Why use a number when a single word will do? You can use the keywords left, center, and right, as well as top, center, and bottom, for 0%, 50%, and 100%, respectively. To center an image in the tag's content area, use:

background-position: center

You can mix and match length and percentage values,[] too, so that:

[] That is, if the browser supports the value units. So far, Internet Explorer and Netscape support only a meager repertoire of length unitspixels and percents.

background-position: 1cm 50%

places the image one centimeter to the right of the tag's left edge, centered vertically in the tag's area.

Note that with relative offsets, the image moves relative to the tag's contents when the user resizes the browser display window because the space allotted to the content also gets resized. By contrast, the image stays in the same place relative to the element's contents if you use absolute offset values.

Finally, one might also expect that the repeating background (by default; see the following section, would tile down and to the right of the offset. Not so. Current browsers "wrap" the image around to fill the element's allotted display space. For example, look closely at Figure and notice the tiling effects for an offset versus nonoffset background image displayed from the following example style fragments:

<style type=css/text>
pre {background-image: url(backgrounds/vert.gif)}
pre.offset {background-image: url(backgrounds/vert.gif); background-position: -20px
The following background image is offset by -20 pixels left and up:
<pre class=offset>

This background image is not offset:


Background-offset with tiling

The background-repeat property

Normally, the browser tiles a background image to fill the allotted space, repeating the image both horizontally and vertically. Use the background-repeat property to alter this repeat (default value) behavior. To have the image repeat horizontally but not vertically, use the value repeat-x. For only vertical repetition, use repeat-y. To suppress tiling altogether, use no-repeat.

A common use of this property is to place a watermark or logo in the background of a page without repeating the image over and over. For instance, this code places the watermark image in the background at the center of the page:

body {background-image: url(backgrounds/watermark.gif);
      background-position: center center;
      background-repeat: no-repeat

A popular trick is to create a vertical ribbon down the righthand side of the page:

body {background-image: url(backgrounds/ribbon.gif);
      background-position: top right;
      background-repeat: repeat-y

The background property

Like the various font properties, the many background CSS2 properties can get cumbersome to write and hard to read later. So, like the font property, there is also a general background property.

The background property accepts values from any and all of the background-color, background-image, background-attachment, background-repeat, and background-position properties, in any order. If you do not specify values for some of the properties, those properties are explicitly set to their default values. Thus:

background: red

sets the background-color property to red and resets the other background properties to their default values. A more complex example:

background: url(backgrounds/marble.gif) blue repeat-y fixed center

sets all the background image and color properties at once, resulting in a marble image on top of a blue background (blue showing through any transparent areas). The image repeats vertically, starting from the center of the content display area, and does not scroll when the user scrolls the display. Notice that we include just a single position value (center), and the browser uses it for both the vertical and horizontal positions.

The color property

The color property sets the foreground color for a tag's contentsthe color of the text lettering, for instance. Its value is either the name of a color, a hexadecimal RGB triple, or a decimal RGB triple, as outlined earlier in section The following are all valid property declarations:

color: mauve
color: #ff7bd5
color: rgb(255, 125, 213)
color: rgb(100%, 49%, 84%)

Generally, you'll use the color property with text, but you may also modify nontextual content of a tag. For instance, the following example produces a green horizontal rule:

hr {color: green}

If you don't specify a color for an element, it inherits the color of its parent element.

Text Properties

Cascading stylesheets make a distinction between font properties, which control the size, style, and appearance of text, and text properties, which control how text is aligned and presented to the user.

The letter-spacing property

The letter-spacing property puts additional space between text letters as they are displayed by the browser. Set the property with either a length value or the default keyword normal, indicating that the browser should use normal letter spacing. For example:

blockquote {letter-spacing: 2px}

puts an additional two pixels between adjacent letters within the <blockquote> tag. Figure illustrates what happens when you put five pixels between characters.

The letter-spacing property lets you stretch text

All the popular browsers support this property.

The line-height property

Use the line-height property to define the minimum spacing between lines of a tag's text content. Normally, browsers single-space text linesthe top of the next line is just a few points below the last line. By adding to that line height, you increase the amount of space between lines.

The line-height value can be an absolute or a relative length, a percentage, a scaling factor, or the keyword normal. For example:

p {line-height: 14pt}
p {line-height: 120%}
p {line-height: 2.0}

The first example sets the line height to exactly 14 points between baselines of adjacent lines of text. The second computes the line height to 120 percent of the font size. The last example uses a scaling factor to set the line height to twice as large as the font size, creating double-spaced text. The value normal, the default, is usually equal to a scaling factor of 1.0 to 1.2.

Keep in mind that absolute and percentage values for line-height compute the line height based on the value of the font-size property. Children of the element inherit the computed property value. Subsequent changes to font-size by either the parent or the child elements do not change the computed line height.

Scaling factors, on the other hand, defer the line-height computation until the browser actually displays the text. Hence, varying font sizes affect line height locally. In general, it is best to use a scaling factor for the line-height property so that the line height changes automatically as the font size changes.

Although it is usually considered separate from font properties, you may include this text-related line-height property's value as part of the shorthand notation of the font property. [The font property,]

The text-align property

Text justified with respect to the page margins is a rudimentary feature of nearly all text processors. The text-align property brings that capability to HTML for any block-level tag. (The W3C standards people prefer that you use CSS2 text-align styles rather than the explicit align attribute for block-level tags such as <div> and <p>.) Use one of four values: left, right, center, or justify. The default value is, of course, left.[*]

[*] For left-to-right locales. In right-to-left locales, the default is right.

For example:

div {text-align: right}

tells the styles-conscious browser to align all the text inside <div> tags against the right margin. The justify value tells the browser to align the text to both the left and right margins, spreading the letters and words in the middle to fit.

All the popular browsers currently support the left, right, and center alignments, but not justify.

The text-decoration property

The text-decoration property produces text embellishments, some of which are also available with the original physical style tags. Its value is one or more of the keywords underline, overline, line-through, and blink. The value none is the default, which tells the styles-conscious browser to present text normally.

The text-decoration property is handy for defining different link appearances:

a:visited, a:link, a:active {text-decoration: underline overline}

This puts lines above and below the links in your document.

This text property is not inherited, and nontextual elements are not affected by the text-decoration property.

Interestingly, all the popular browsers support the text-decoration property, but only Internet Explorer has the good taste not to support its blink value.

The text-indent property

Although less common today, it is still standard practice to indent the first line of a paragraph of text.[*] And some text blocks, such as definitions, typically "out-dent" the first line, creating what is called a hanging indent.

[*] But not, obviously, in this book.

The CSS2 text-indent property lets you apply these features to any block tag and thereby control the amount of indentation of the first line of the block. Use length and percentage values: negative values create the hanging indent, and percentage values compute the indentation as a percentage of the parent element's width. The default value is 0.

To indent all the paragraphs in your document, for example, you could use:

p {text-indent: 3em}

The length unit em scales the indent as the font of the paragraph changes in size on different browsers.

Hanging indents are a bit trickier, because you have to watch out for the element borders. Negative indentation does not shift the left margin of the text; it simply shifts the first line of the element left, possibly into the margin, border, or padding of the parent element. For this reason, hanging indents work as expected only if you also shift the left margin of the element to the right by an amount equal to or greater than the size of the hanging indent. For example:

p.wrong {text-indent: -3em}
p.hang {text-indent: -3em; margin-left: 3em}
p.large {text-indent: -3em; margin-left: 6em}

creates three paragraph styles. The first creates a hanging indent that extends into the left margin, the second creates a conventional hanging indent, and the third creates a paragraph whose body is indented more than the hanging indent. Figure shows all three styles in use.

The effects of text-indent and margin-left on a paragraph

All the popular browsers support the text-indent property.

The text-shadow property

The text-shadow property lets you give your text a three-dimensional appearance through the time-honored use of shadowing. Values for the property include a required offset and optional blur radius and color. The property may include more than one set of values, separated with commas, to achieve a stack of shadows, with each subsequent set of values layered on top of the previous one but always beneath the original text.

The property's required offset is composed of two length values: the first specifies the horizontal offset, and the second specifies the vertical offset. Positive values place the shadow to the right and below the respective length distance from the text. Negative values move the shadow left and up, respectively.

The optional blur radius is also a length value that specifies the boundaries for blurring, an effect that depends on the rendering agent. The other shadow value is color. This, of course, may be an RGB triple or color name, as for other properties, and specifies the shadow color. If you don't specify this value, text-shadow uses the color value of the color property. For example:

h1 {text-shadow; 10px 10px 2px yellow}
p:first-letter {text-shadow: -5px -5px purple, 10px 10px orange}

The first text-shadow example puts a 2-pixel blurred-yellow shadow behind, 10 pixels below, and 10 pixels to the right of level-1 headers in your document. The second example puts two shadows behind the first letter of each paragraph. The purple shadow sits 5 pixels above and 5 pixels to the left of that first letter. The other shadow, like in the first example (although orange in this case), goes 10 pixels to the right and 10 pixels below the first letter of each paragraph.

Unfortunately, we can't show you any of these effects, because none of the popular browsers supports this property.

The text-transform property

The text-TRansform property lets you automatically convert portions or all of your document's text into uppercase or lowercase lettering. Acceptable values are capitalize, uppercase, lowercase, and none.

capitalize renders the first letter of each word in the text into uppercase, even if the source document's text is in lowercase. The uppercase and lowercase values respectively render all the text in the corresponding case. none, of course, cancels any transformations. For example:

h1 {text-transform: uppercase}

formats all the letters in level-1 headers, presumably titles, in uppercase text, whereas:

h2 {text-transform: capitalize}

makes sure that each word in level-2 headers begins with a capital letter, a convention that might be appropriate for section heads, for instance.

Note that while uppercase and lowercase affect the entire text, capitalize affects only the first letter of each word in the text. Consequently, transforming the word "htMl" with capitalize generates "HtMl."

All the popular browsers support the text-TRansform property.

The vertical-align property

The vertical-align property controls the relative position of an element with respect to the line containing the element. Valid values for this property include:


Align the baseline of the element with the baseline of the containing element.


Align the middle of the element with the middle (usually the x-height) of the containing element.


Subscript the element.


Superscript the element.


Align the top of the element with the top of the font of the parent element.


Align the bottom of the element with the bottom of the font of the parent element.


Align the top of the element with the top of the tallest element in the current line.


Align the bottom of the element with the bottom of the lowest element in the current line.

In addition, a percentage value indicates a position relative to the current baseline so that a position of 50% puts the element halfway up the line height above the baseline. A position value of -100% puts the element an entire line height below the baseline of the current line.

All the popular browsers agree on where to place images relative to a line of text for baseline (default and the same as no vertical-align specification), middle (but not center), super (but not sub), text-top, text-bottom, top (same as text-top; but not bottom), and for both plus and minus percentage offset values. Figure shows you how Internet Explorer treats the various vertical-align values.

Internet Explorer's treatment of the vertical alignment property values

For the differences, Firefox treats center like Internet Explorer and different from middle (Figure), whereas Netscape treats center identical to middle, but Opera doesn't recognize the value at all. With sub, it's Netscape's turn to agree with Firefox and place the bottom of the subscripted image at the bottom of the character descender, whereas Opera places the bottom of the image perceptively below the baseline, but unlike Internet Explorer, not so low as to be just above the next line of text.

With the bottom value, it's Opera's turn to agreewith Internet Explorer, aligning the bottom of the image with the bottom of the line just above the next line of text, whereas Firefox and Netscape place the bottom of the image at the bottom of the character descender. Clear as mud? Perhaps Figures 8-11 through 8-13 will help you to visualize the differences when also compared with Figure.

Firefox's rendering of selected vertical-align values

Opera's rendering of selected vertical-align values

Netscape's rendering of selected vertical-align values

The word-spacing property

Use the word-spacing property to add space between words within a tag. You can specify a length value, or use the keyword normal to revert to normal word spacing. For example:

h3 {word-spacing: 25px}

places an additional 25 pixels of space between words in the <h3> tag.

All the currently popular browsers support the word-spacing property.

Box Properties

The CSS2 model assumes that HTML and XHTML elements always fit within rectangular boxes. Using the properties defined in this section, you can control the size, appearance, and position of the boxes containing the elements in your documents.

The CSS2 formatting model

Each element in a document fits into a rectangular space or box. The CSS2 authors call this box the core content area and surround it with three more boxes: the padding, the border, and the margin. Figure shows these boxes and defines some useful terminology.

The CSS2 formatting model and terminology

The top, bottom, left-outer, and right-outer edges bound the content area of an element and all of its padding, border, and margin spaces. The inner-top, inner-bottom, left-inner, and right-inner edges define the sides of the core content area. The extra space around the element is the area between the inner and outer edges, including the padding, border, and margin. A browser may omit any and all of these extra spaces for any element, and for many, the inner and outer edges are the same.

When elements are vertically adjacent, the bottom margin of the upper elements and the top margin of the lower elements overlap so that the total space between the elements is the greater of the adjacent margins. For example, if one paragraph has a bottom margin of 1 inch, and the next paragraph has a top margin of 0.5 inches, the greater of the two margins, 1 inch, is placed between the two paragraphs. This practice is known as margin collapsing and generally results in better document appearance.

Horizontally adjacent elements do not have overlapping margins. Instead, the CSS2 model adds together adjacent horizontal margins. For example, if a paragraph has a left margin of 1 inch and is adjacent to an element with a right margin of 0.5 inches, the total space between the two is 1.5 inches. This rule also applies to nested elements so that a paragraph within a division has a left margin equal to the sum of the division's left margin and the paragraph's left margin.

As shown in Figure, the total width of an element is equal to the sum of seven items: the left and right margins, the left and right borders, the left and right padding, and the element's content itself. The sum of these seven items must equal the width of the containing element. Of these seven items, only three (the element's width and its left and right margins) can be given the value auto, indicating that the browser can compute a value for that property. When this becomes necessary, the browser follows these rules:

  • If none of these properties is set to auto and the total width is less than the width of the parent element, the margin-right property is set to auto and made large enough to make the total width equal to the width of the parent element.

  • If exactly one property is set to auto, that property is made large enough to make the total width equal to the width of the parent element.

  • If width, margin-left, and margin-right are set to auto, the CSS2-compliant browser sets both margin-left and margin-right to 0 and sets width large enough to make the total equal to the width of the parent element.

  • If both the left and right margins are set to auto, they are always set to equal values, centering the element within its parent.

There are special rules for floating elements. A floating element (such as an image with align=left specified) does not have its margins collapsed with the margins of containing or preceding elements, unless the floating element has negative margins. Figure shows how the following bit of HTML might be rendered:

<img align=left src="pics/img.gif">
Some sample text...

Handling the margins of floating elements

The browser moves the image, including its margins, as far as possible to the left and toward the top of the paragraph without overlapping the left and top margins of the paragraph or the document body. The left margins of the paragraph and the containing body are added, and their top margins are collapsed.

The border properties

The border surrounding an element has a color, a thickness, and a style. You can use various properties to control these three aspects of the border on each of the four sides of an element. Shorthand properties make it easy to define the same color, thickness, and style for the entire border, if desired. Border properties are not inherited; you must explicitly set them for each element that has a border.

The border-color property

Use the border-color property to set the border color. If this property is not specified, the browser draws the border using the value of the element's color property.

The border-color property accepts from one to four color values. The number of values determines how they are applied to the borders (summarized in Figure). If you include just one property value, all four sides of the border are set to the specified color. Two values set the top and bottom borders to the first value and the left and right borders to the second value. With three values, the first is the top border, the second sets the right and left borders, and the third color value is for the bottom border. Four values specify colors for the top, right, bottom, and left borders, in that order.

Order of effects for multiple border, margin, and padding property values

Number of values

Affected border(s), margin(s), or padding


All items have the same value.


The first value sets top and bottom; the second value sets left and right.


The first value sets top; the second sets both left and right; the third value sets bottom.


The first value sets top; the second sets right; the third sets bottom; the fourth value sets left.

The border-width property

The border-width property lets you change the width of the border. Like the border-color property, it accepts from one to four values that are applied to the various borders in a similar manner (refer to Figure).

Besides a specific length value, you may also specify the width of a border as one of the keywords thin, medium, or thick. The default value, if the width is not explicitly set, is medium. Some typical border widths are:

border: 1px
border: thin thick medium
border: thick 2mm

The first example sets all four borders to exactly 1 pixel. The second makes the top border thin, the right and left borders thick, and the bottom border medium. The last example makes the top and bottom borders thick and the right and left borders 2 millimeters wide.

If you are uncomfortable defining all four borders with one property, you can use the individual border-top-width, border-bottom-width, border-left-width, and border-right-width properties to define the thickness of each border. Each property accepts just one value; the default is medium.

All the currently popular browsers support this property.

The border-style property

According to the CSS2 model, you may apply a number of embellishments to your HTML element borders.

The border-style property values include none (default), dotted, dashed, solid, double, groove, ridge, inset, and outset. The border-style-conscious browser applies one to four values for the property to each border, in the same order as for the border colors and widths, as described in Figure.

The browser draws dotted, dashed, solid, and double borders as flat lines on top of the tag's background. The groove, ridge, inset, and outset values create three-dimensional borders: the groove is an incised line, the ridge is an embossed line, the inset border makes the entire tag area appear set into the document, and the outset border makes the entire tag area appear raised above the document. The effect of the three-dimensional nature of these last four styles on the tag's background image is undefined and left up to the browser. Netscape supports three-dimensional effects.

All the currently popular browsers support the border styles. An example is shown in Figure.

The border-style property nicely frames images

Borders in shorthand

Specifying a complex border can get tedious, so the CSS2 standard provides five shorthand properties that accept any or all of the width, color, and style values for one or all of the border edges. The border-top, border-bottom, border-left, and border-right properties affect their respective borders' sides; the comprehensive border property controls all four sides of the border simultaneously. For example:

border-top: thick solid blue
border-left: 1ex inset
border-bottom: blue dashed
border: red double 2px

The first property makes the top border a thick, solid, blue line. The second sets the left border to use an inset effect that is as thick as the x-height of the element's font, while leaving the color the same as the element's color. The third property creates a blue dashed line at the bottom of the element, using the default medium thickness. Finally, the last property makes all four borders a red double line, 2 pixels thick.

That last property raises two issues. First, you cannot supply multiple values to the border property to selectively affect certain borders, as you can with the individual border-color, border-width, and border-style properties. The border property always affects all four borders around an element.

Second, a bit of reflection should reveal that it is not possible to create a double-line border just 2 pixels thick. In cases like this, the browser is free to adjust the thickness to render the border properly.

While we usually think of borders surrounding block elements such as images, tables, and text flows, you also can apply borders to inline tags. This lets you put a box around a word or phrase within a text flow. The implementation of borders on inline tags that span multiple lines is undefined and left to the browser.

All of the currently popular browsers support the border styles.

The clear property

Like its cousin attribute for the <br> tag, the clear property tells the browser whether to place a tag's contents adjacent to a "floating" element or on the first line below it. Text flows around floating elements such as images and tables with an align=left or align=right attribute or any HTML/XHTML element with its float property set to anything but none. [<br>, 4.6.1] [The float property,]

The value of the clear property can be none, left, right, or both. A value of none, the default, means that the browser acts normally and places the tag's contents adjacent to floating elements on either side, if there is room to do so. The value left prevents contents from being placed adjacent to a floating element on its left; right prevents placement on the right side of a floating element; and both prevents the tag's contents from appearing adjacent to any floating element.

The effect of this style is the same as preceding the tag with a <br> tag with its clear attribute set. Hence:

h1 {clear: left}

has the same effect as preceding every <h1> tag with <br clear=left>.

The clip property

Normally, the content of an element is completely visible within the display space of the element. The clip property defines a viewing window within an element's display space, letting you hide unwanted elements and focus attention on some area or aspect of the content.

The default value of the clip property is auto, meaning that the viewing window matches the box of the element. Instead, you may specify a shape that creates a distinct viewing window into the element's display area. Currently, the only shape supported by CSS2[*] is a rectangle, denoted by the rect keyword. For example:

[*] Presumably, future versions of the standard will expand to include other shapes.

p {overflow : hidden;
   clip : rect(15px, -10px, 5px, 10px) }

The four values define the top, right, bottom, and left edges of the clipping rectangle. Each value is an offset relative to the box edges defined for the element. So, in this example, the top of the clipping area is 15 pixels below the top of the element's box, the right edge is 10 pixels to the right of the box, the bottom is 5 pixels above the bottom of the box, and the left edge is 10 pixels to the right of the left side of the box.

Note that the clip property takes effect only when the overflow property of an element is set to some value other than visible. When overflow is set to visible, no clipping occurs and the clip property is ignored.

The popular browsers don't yet support the clip property.

The float property

The float property designates a tag's display space as a floating element and causes text to flow around it in a specified manner. It is generally analogous to the align attribute for images and tables, but you can apply it to any element, including text. [The align attribute (deprecated),]

The float property accepts one of three values: left, right, or none (the default). Using none disables the float property. The others work like their align attribute-value counterparts, telling the browser to place the content to either side of the flow and allow other content to be rendered next to it.

Accordingly, the browser places a tag's contents (including its margins, padding, and borders) specified with float: left against the left margin of the current text flow, and subsequent content flows to its right, down and below the tag's contents. The float: right pair puts the tag contents against the right edge of the flow and flows other content on its left, down and below the tag's contents.

Although the float property is most commonly used with tables and images, it is perfectly acceptable to apply it to a text element. For example, the following creates a "run-in" header, with the text flowing around the header text, as shown in Figure:

h2 {float: left;
text-align: center;
margin-right: 10px }

Use the float property with text blocks to create run-in headers

All the popular browsers support this property.

The height property

As you might suspect, the height property controls the height of the associated tag's display region. You'll find it most often used with images and tables, but you can use it to control the height of other document elements as well.

The value of the height property is either a length value or the keyword auto (the default). Using auto implies that the affected tag has an initial height that should be used when displaying the tag. Otherwise, the height of the tag is set to the desired height. If an absolute value is used, the height is set to that length value. For example:

img {height: 100px}

tells the browser to display the image referenced by the <img> tag scaled so that it is 100 pixels tall. If you use a relative value, the base size to which it is relative is browser and tag dependent.

When scaling elements to a specific height, you can preserve the aspect ratio of the object by also setting the width property of the tag to auto. Thus:

img {height: 100px; width: auto}

ensures that the images are always 100 pixels tall, with an appropriately scaled width. [The width property,]

If you want to constrain the height of an element to a range rather than a specific value, use the min-height and max-height properties. These properties accept values like the height property and establish a range for the height of the element. The browser then adjusts the height of the element to fall within the desired range.

All of the popular browsers fully support the height property, but none of the browsers yet supports the min-height and max-height properties.

The margin properties

Like the border properties, the various margin properties let you control the margin space around an element, just outside of its border (see Figure). Margins are always transparent, allowing the background color or image of the containing element to show through. As a result, you can specify only the size of a margin; it has no color or rendered style.

The margin-left, margin-right, margin-top, and margin-bottom properties all accept a length or percentage value indicating the amount of space to reserve around the element. In addition, the keyword auto tells the styles-conscious browser to revert to the margins it normally would place around an element. Percentage values are computed as a percentage of the containing element's width. The default margin, if not specified, is 0.

These are all valid margin settings:

body {margin-left: 1in; margin-top: 0.5in; margin-right: 1in}
p {margin-left: -0.5cm}
img {margin-left: 10%}

The first example creates 1-inch margins down the right and left edges of the entire document and a 0.5-inch margin across the top of the document. The second example shifts the left edge of the <p> tag 0.5 centimeters left, into the left margin. The last example creates a margin to the left of the <img> tag equal to 10 percent of the parent element's width.

As you can the shorthand border property, you can use the shorthand margin property to define all four margins, using from one to four values, which affect the margins in the order described in Figure. Using this notation, our <body> margins in the previous example could also have been specified as:

body {margin: 0.5in 1in}

The margin-left and margin-right properties interact with the width property to determine the total width of an element, as described earlier in section

All the popular browsers support the margin properties and values.

The padding properties

Like the margin properties, the various padding properties let you control the padding space around an element, between the element's content area and its border (see Figure, earlier in the chapter).

Padding always is rendered using the background color or image of the element. As a result, you can specify only the size of the padding; it has no color or rendered style.

The padding-left, padding-right, padding-top, and padding-bottom properties all accept a length or percentage value indicating the amount of space the styles-conscious browser should reserve around the element. Percentage values are computed as a percentage of the containing element's width. Padding can never be negative. The default padding is 0.

These are valid padding settings:

p {padding-left: 0.5cm}
img {padding-left: 10%}

The first example creates 0.5 centimeters of padding between the contents of the <p> tag and its left border. The second example creates padding to the left of the <img> tag equal to 10 percent of the parent element's width.

Like the shorthand margin and border properties, you can use the shorthand padding property to define all four padding amounts, using from one to four values to affect the padding sides as described in Figure. Internet Explorer does not support the padding property, but all the other popular browsers do.

The overflow property

The overflow property tells the browser how to handle content that overflows the display area of an element. The default value of this property, visible, tells the browser to render all content, making it visible even if it falls outside of the element's display area.

Erring on the side of caution, you most often want the browser to display all of your document's contents. But in rare cases, elements may overlap, creating an ugly display. To prevent such mishaps, set the overflow property to either hidden, scroll, or auto.

The hidden value forces the browser to hide all content that overflows its allotted space, making it invisible to the user. The value scroll creates scroll bars for the element, which viewers may use to see the hidden content. However, scroll bars are added to the element even if the content does not overflow.

Adding permanent scroll bars ensures that the scroll bars do not come and go as the content of the element changes in size in a dynamic document. The downside to this is the clutter and distractions that scroll bars create. Avoid all this with the auto value for the overflow property. When on auto, scroll bars appear only when they are needed. If the element's content changes so that it is not clipped, the scroll bars are removed from the element.

None of the currently popular browsers supports the overflow property.

The position properties

Without intervention, the browser flows document elements together, positioned sequentially through the display. You can change this standard behavior with the CSS2 position property, in conjunction with the top, bottom, left, and right properties.

If the position property is set to static, conventional HTML/XHTML layout and positioning rules apply, with the left and top edges of the element's box determined by the browser. To shift an element with respect to its containing flow, set the position property to relative. In this case, the top, bottom, left, and right properties are used to compute the box position relative to its normal position in the flow. Subsequent elements are not affected by this position change and are placed in the flow as though this element had not been shifted.

Setting the position property to absolute removes the element from the containing flow, allowing subsequent elements to move up accordingly. The position of the element is then computed relative to the containing block, using the top, bottom, left, and right properties. This type of positioning allows an element to be placed in a fixed position with respect to its containing element but to move as that containing element moves.

Finally, setting the position property to fixed positions an element with respect to the window or page in which it is displayed. Like absolute positioning, the element is removed from the containing flow, with other elements shifting accordingly. The top, bottom, left, and right properties are used to set the element's position with respect to the containing window or page. Note that for continuous media (such as a scrolling browser display), the element is displayed once at the desired position. For printed media, the element is printed on each page at the desired position. You might used fixed positioning to place headers and footers at the top and bottom of the browser window or at the top and bottom of each printed page.

The top, bottom, left, and right properties each accept a length or percentage value. When the position attribute is set to relative, the percentage is based on the size of the element's box. When position is set to absolute or fixed, the percentage is based on the size of the containing element's box. When length values are used, they specify offsets from the corresponding edge of the element's containing box. For example, to position an element such that its bottom is 1 centimeter above the bottom of the browser window (or each printed page), you would set the position property to fixed and the bottom property to 1cm.

The visibility property

The visibility property determines whether the contents of an element are visible in the display. The space set aside for the element is still created and affects the layout of the document, but the content of the element may be made invisible within that space.

The default value for this property, visible, causes the element's content to be displayed. Setting this property to hidden makes the content invisible without removing the element's display box, altering the layout of the document. Note that you can remove an element's content and display box from the document by setting the display property to none.

This property is often used in dynamic documents, where changing its value for an element removes its content from the display without reformatting the document.

When this property is used in conjunction with table rows, row groups, columns, and column groups, you may also specify the value collapse. Used in this context, the collapse value removes the associated row(s) or column(s) from the table without otherwise reformatting or redrawing the table. Within dynamic documents, this lets you remove elements from a table without reformatting the entire table. Used outside of a table, the collapse value has the same effect as the hidden value.

The width property

The width property is the companion to the height property and controls the width of an associated tag. Specifically, it defines the width of the element's content area, as shown in Figure. You'll see it most often used with images and tables, but you could conceivably use it to control the width of other elements as well.

The value for the width property is either a length or percentage value, or the keyword auto. The value auto is the default and implies that the affected tag has an initial width that should be used when displaying the tag. If a length value is used, the width is set to that value; percentage values compute the width to be a percentage of the width of the containing element. For example:

img {width: 100px}

displays the image referenced by the <img> tag scaled to 100 pixels wide.

When scaling elements to a specific width, the aspect ratio of the object is preserved if the height property of the tag is set to auto. Thus:

img {width: 100px; height: auto}

makes all the images 100 pixels wide and scales their heights appropriately. [The height property,]

If you want to constrain the width of an element to a range rather than a specific value, use the min-width and max-width properties. These properties accept values like the width property and establish a range for the width of the element. The browser then adjusts the width of the element to fall within the desired range.

The width property interacts with the margin-left and margin-right properties to determine the total width of an element, as described earlier in section

The z-index property

In addition to the x and y positions of an element within the browser window or on the printed page, each element has a vertical, or z, position. Elements with higher z positions are "closer" to the viewer and obscure elements underneath them.

Z positions are not absolute throughout a document. Instead, z positions are relative to the containing element. For example, two <div> elements within a document might be positioned to lie on top of one another. The first <div> might have a z position of 1, and the second might have a z position of 2. The entire contents of the second <div> are displayed over (or in front of ) the first <div>. If elements within the first <div> have z positions of 3 or 4, they are still displayed within their containing <div>s and do not "jump out" in front of the second <div>.

You control the z position of an element with the z-index property. The value of the z-index property is a positive integer that sets the z position of the element with respect to its containing element. With the z-index property, you can dynamically alter the z position of an element to make it visible, or position a text element in front of an image to label items of interest.

List Properties

The CSS2 standard also lets you control the appearance of list elementsspecifically, ordered and unordered lists. Browsers format list items just like any other block item, except that the block has some sort of marker preceding the contents. For unordered lists, the marker is a bullet of some sort; for numbered lists, the marker is a numeric or alphabetic character or symbol. The CSS2 list properties let you control the appearance and position of the marker associated with a list item.

The list-style-image property

The list-style-image property defines the image that the browser uses to mark a list item. The value of this property is the URL of an image file or the keyword none. The default value is none.

The image is the preferred list marker. If it is available, the browser displays it in place of any other defined marker. If the image is unavailable, or if the user has disabled image loading, the browser uses the marker defined by the list-style-type property (see section, later in this chapter).

HTML/XHTML authors use the list-style-image property to define custom bullets for their unordered lists. While you conceivably could use any image as a bullet, we recommend that you keep your marker GIF or JPEG images small, to ensure attractively rendered lists.

For example, by placing the desired bullet image in the file mybullet.gif on your server, you could use that image:

li {list-style-image: url(pics/mybullet.gif); list-style-type: square}

In this case, the browser uses the image if it is able to successfully download mybullet.gif. Otherwise, the browser uses a conventional square bullet.

All the popular browsers support the list-style-image property, as shown in Figure.

The list-style-image property lets you use your own bullets

The list-style-position property

There are two ways to position the marker associated with a list item: inside the block associated with the item or outside the block. Accordingly, the list-style-position property accepts one of two values: inside or outside.

The default value is outside, meaning that the item marker hangs to the left of the item, like this:

•This is a bulleted 
 with an "outside" marker

The value inside causes the marker to be drawn with the list item flowing around it, much like a floating image:

•This is a bulleted list
 with an "inside" marker

Notice that the second line of text is not indented but instead lines up with the left edge of the marker.

The current versions of the popular browsers fully support the list-style-position property.

The list-style-type property

The list-style-type property serves double duty in a sense, determining how a styles-conscious browser renders both ordered and unordered list items. The property has the same effect as the type attribute on a list item. [The type attribute,]

When applied to items within an unordered list, the list-style-type property uses one of four valuesdisc, circle, square, or noneand marks the unordered list items with a corresponding dingbat. The default value of a level-1 list item is disc, although browsers change that default depending on the nesting level of the list.

When applied to items within an ordered list, the list-style-type property uses one of six valuesdecimal, lower-roman, upper-roman, lower-alpha, upper-alpha, or nonecorresponding to the item numbers expressed as decimal values, lowercase Roman numerals, uppercase Roman numerals, lowercase letters, uppercase letters, or with no style, respectively. Most browsers use decimal numbering as the default.

The popular browsers support list-style-type as well as the list-style property described in the next section.

The list-style property

The list-style property is the shorthand version for all the other list-style properties. It accepts any or all of the values allowed for the list-style-type, list-style-position, and list-style-image properties, in any order and with values appropriate for the type of list they are to affect. These are valid list-style properties:

li {list-style: disc}
li {list-style: lower-roman inside}
li {list-style: url( square}

The first example creates list items that use a disc as the bullet image. The second causes numbered list items to use lowercase Roman numerals, drawn inside the list item's block. In the last example, the styles-conscious browser uses a square as the bullet image if the referenced image is unavailable.

Using list properties effectively

Although you can apply list properties to any element, they affect only the appearance of elements whose display property is set to list-item. Normally, the only tag with this property is the <li> tag.

However, this shouldn't deter you from using these properties elsewhere, particularly with the <ul> and <ol> tags. Because these properties are inherited by elements whose parents have them set, modifying a list property for the <ul> and <ol> tags subsequently modifies it for all the <li> tags contained within that list. This makes it much easier to define lists with a particular appearance.

For example, suppose you want to create a list style that uses lowercase Roman numerals. One way is to define a class of the <li> tag with the appropriate list-style-type defined:

li.roman {list-style-type: lower-roman}

Within your list, you'll need to specify each list element using that class:

  <li class=roman>Item one
  <li class=roman>Item two
  <li class=roman>And so forth

Having to repeat the class name is tedious and error-prone. A better solution is to define a class of the <ol> tag:

ol.roman {list-style-type: lower-roman}

Any <li> tag within the list inherits the property and uses lowercase Roman numerals:

<ol class=roman>
  <li>Item one
  <li>Item two
  <li>And so forth

This is much easier to understand and manage. If you want to change the numbering style later, you need only change the <ol> tag properties, instead of finding and changing each instance of the <li> tag in the list.

You can use these properties in a much more global sense, too. Setting a list property on the <body> tag changes the appearance of all lists in the document; setting it on a <div> tag changes all the lists within that division.

Table Properties

For the most part, HTML/XHTML browsers render table content using the same properties that control the rendering of conventional document content. However, a few special circumstances occur only within tables. To give authors greater control over these items, CSS2 has added a few table-specific properties. The popular browsers do not yet support any of them.

The border-collapse, border-spacing, and empty-cells properties

There are two divergent views regarding cell borders within tables. The first view holds that each cell is an independent entity with unique borders. The second view holds that adjacent cells share the border side and that changing a border in one cell should affect the neighboring cell.

To give the most control to authors, CSS2 provides the border-collapse property, which lets you choose the model that suits your style. By default, the value of this property is collapse, meaning adjacent cells share their border style. Alternatively, you can set the border-collapse property to separate, which enlarges the table so that borders are rendered separately and distinctly around each cell.

If you choose the separate model, you can also use the border-spacing property to set the spacing between adjacent borders. The default border spacing is 0, meaning that adjacent cell borders touch each other, although some browsers may use a different default. By increasing this value, you cause the browser to insert additional space between borders, allowing the background color or image of the table to show through. If you specify just one value for border-spacing, it sets the spacing for both horizontal and vertical borders. If you provide two values, the first sets the horizontal spacing and the second determines the vertical spacing.

Within the separate model, you can also control how borders are drawn around empty cells. By default, borders are drawn around every cell in a table, even if it has no content. You can change this by switching the empty-cells property from its default value of show to the value hide. When this property is set, empty cells simply show the table background. If a whole row of cells is empty, the browser removes the row from the table entirely.

The caption-side property

Use the caption-side property only with the <caption> element. It accepts values of top (default), bottom, left, or right, and tells the browser where to place the caption adjacent to its associated table. The caption-side property provides a more consistent method of placing the caption than the browser-dependent and standards-deprecated align attribute of the <caption> tag.

All of the popular browsers, except Internet Explorer, support caption-side.

The speak-header property

An audio-capable browser might offer a number of ways for users to navigate by hearing the contents of a table. A simplistic approach would have the browser read the table contents in order, from top to bottom and right to left. A more sophisticated audio browser organizes the table contents according to their respective headers and reads the information in a more comprehensible manner. To avoid confusion in any case, the browser must provide some way to tell the user which cell it is reading.

The speak-header property provides two ways for a browser to identify a cell or collection of cells in the table. If once (the default) is specified, the browser reads the contents of a header cell only once before proceeding to read the contents of each associated data cell. This way, a user moving across a row of cells would hear the row header and column header of the first cell in the row, but would hear the changing column headers only as she moved to subsequent cells in the row.

If you set the speak-header property to always, the browser prefaces the reading of each cell's contents with a reading of its associated header. This may prove more useful with complex tables or where the header values make it easier to understand the table contentsespecially when a table contains only numbers.

Note that headers are spoken only when the browser knows which header cells are associated with which data cells. Conscientious authors always use the header attribute with their table cells, to specify the header cells related to each data cell in their tables.

The table-layout property

Table layout is a tough task for any browser. To create an attractive table, the browser must find the widest cell in each column, adjust that column to accommodate the width, and then adjust the overall table to accommodate all of its columns. For large tables, document rendering can be noticeably slowed as the browser makes several passes over the table, trying to get things just right.

To help in this process, use the table-layout property. If you set the property to fixed, the browser determines column widths based on the widths of cells in the first row of the table. If you explicitly set the column widths, setting the table's table-layout property to fixed makes the table-rendering process even faster, enhancing the readers' experience as they view your document.

By default, the table-layout property is set to auto, which forces the browser to use the more time-consuming, multiple-pass layout algorithm, even if you specify the widths of your columns in the table. If your table content is variable and you cannot explicitly set the widths, leave the table-layout property set to auto. If you can fix your column widths and your table content is amenable, set table-layout to fixed.

Classification Properties

Classification properties are the most fundamental of the CSS2 style properties. They do not directly control how a styles-conscious browser renders HTML or XHTML elements. Instead, they tell the browser how to classify and handle various tags and their contents as they are encountered.

For the most part, you should not set these properties on an element unless you are trying to achieve a specific effect.

The display property

Every element in an HTML or XHTML document can be classified, for display purposes, as a block item, an inline item, or a list item. Block elements, like headings, paragraphs, tables, and lists, are formatted as separate blocks of text, separate from their previous and following block items. Inline items, like the physical and content-based style tags and hyperlink anchors, are rendered within the current line of text within a containing block. List items, specifically <li>-tagged content, are rendered like block items, with a preceding bullet or number known as a marker.

The display property lets you change an element's display type to block, inline, list-item, or none. The first three values change the element's classification accordingly; the value none turns off the element, preventing it and its children from being displayed in the document.

Conceivably, you could wreak all sorts of havoc by switching element classifications, forcing paragraphs to be displayed as list items and converting hyperlinks to block elements. In practice, this is just puerile monkey business, and we don't recommend that you change element classifications without a very good reason to do so.

All the popular browsers support this property, but Internet Explorer supports only the block and none values.

The white-space property

The white-space property defines how the styles-conscious browser treats whitespace (tabs, spaces, and carriage returns) within a block tag. The keyword value normalthe defaultcollapses whitespace so that one or more spaces, tabs, and carriage returns are treated as a single space between words. The value pre emulates the <pre> tag, in that the browser retains and displays all spaces, tabs, and carriage returns. Finally, the nowrap value tells the browser to ignore carriage returns and not insert automatic line breaks; all line breaking must be done with explicit <br> tags.

Like the display property, the white-space property is rarely used for good purposes. Don't change how elements handle whitespace without a compelling reason for doing so.

Internet Explorer only supports the nowrap value, and the other popular browsers support both pre and nowrap values for the white-space property.

Generated Content Properties

The idea of generated content is not new to HTML. Even the earliest browsers automatically appended appropriate bullets or numbers to enhance the readability of your unordered and ordered list items. Such features are hardly enough, though, and authors have wished for better content-generation tools in HTML. CSS2 finally comes through, giving authors the ability to create arbitrary content, numbered lists, and all sorts of element-based content.

The foundation of the CSS2 generated-content model is the content and quotes properties, along with the :before and :after pseudoelements. You use the former to define the content you need, and use the latter to position that content with respect to the elements in your document.

The :before and :after pseudoelements

We introduced you to pseudoelements earlier in this chapter, and you even saw some in action (refer to Figures 8-2 and 8-3). The :before and :after pseudoelements operate similarly. Append either to a style-element selector to select and specify the content and properties of generated content in your document. In general, any content created within these pseudoelements inherits the display attributes of the parent element, such that fonts, sizes, and colors applied to an element are also applied to its generated content. For example:

p.note { color : blue }
p.note:before { content : "Note: " }

This style example inserts the word Note: before every <p class=note> element. The inserted text is rendered in blue, like the rest of the paragraph. Replacing it with this style would color the inserted text red, and the remainder of the note would be blue:

p.note:before {content : "Note: "; color : red}

Any generated content, before or after an element, is included in the box of an element and affects its formatting, flow, size, and layout.

The content property

The content property accepts a wide variety of values, ranging from simple strings to automatic counter references. You can include any number of these values, separated by spaces, in a single content property. The browser concatenates the values to form a single value that it then inserts into the document.

The simplest of content values is a quote-enclosed string. You may not include HTML or XHTML markup in the string. Rather, use escape sequences to generate special text (e.g., \A, which generates a line break).

CSS2 escape sequences are like HTML/XHTML character entities. Whereas character entities begin with the ampersand (&), followed by the name or decimal value of a character (# suffix for the latter), you create the same characters for CSS2 string-content property values by preceding the hexadecimal equivalent of the character with a backslash (\). The escape sequence \A is the same as the character entity &#010, which, if you consult Appendix F, you'll find is the line-feed character.

The content property also accepts URL values. Expressed in styles, not HTML-like fashion, the URL may point to any object acceptable to the browser, including text, images, and sound files. For example, to place a decorative symbol next to each equation in a document, you might use:

p.equation:before { content : url("") }

Keep in mind that the object shouldn't contain HTML/XHTML markup because the browser inserts its contents verbatim into the document.

The content property also supports automatic generation of contextually correct, locale-specific quotation marks. You insert them using the open-quote and close-quote keywords. These keywords insert the appropriate quotation mark and increment or decrement, respectively, the browser's nested quotation counter. You can control the appearance of the quotation marks using the quotes property, described shortly. You may also use the no-open-quote and no-close-quote keywords, which increment or decrement the nesting depth without inserting a quotation mark.

A clever feature of the content property is its ability to have the browser render the value of any attribute of its associated element. The attr value has a single parameter, corresponding to the name of an attribute. If that attribute is defined for the element, its value is inserted into the document. To display the URL of an image after the image, for instance, you might write:

img:after { content : "("attr(src) ") " }

If the attribute is not defined for the element, no content gets inserted, although the other values for the content property (like the parentheses we included in the earlier example) would still be inserted.

One of the most powerful features of the content property is its ability to create numbered lists. We cover this in detail in the upcoming section,

All the popular browsers support the :before and :after pseudoelements, but Internet Explorer does not support the content property.

Specifying quotation marks

While you insert quotation marks using the open-quote and close-quote values with the content property, you control the actual characters used for quotation marks with the quotes property.

The value of this property is one or more pairs of strings. The first pair defines the open and close quotation marks for the outermost level of quotations in your document. The next pair specifies the next level, and so forth. If the quotation level exceeds the supplied pairs of characters, the browser starts over with the outermost pair. Note that while most languages use single characters as quotation marks, you can specify strings of any length to be used as quotation marks.

You may also want to specify alternative quotation marks based on the language used. You can use the :lang pseudoelement to associate different quotes properties with different languages. For example:

q:lang(en) { quotes : '"' '"' "'" "'" }
q:lang(no) { quotes : "" "" "<" ">" }

ensures that English and Norwegian documents use their respective quotation marks.

Creating counters

You can create simple numbered lists easily in HTML and XHTML with the <ol> element. More complex numbered lists, especially nested numbered lists, are impossible with the markup languages, though. Instead, CSS2 provides the notion of a counter whose value can be set and changed as the browser renders your document. Insert the value of the counter using special functions recognized by the content property, and alter the appearance and format of the counter with other CSS2 properties.

Every CSS2 counter has a name. To create a counter, simply mention its name in the counter-reset or counter-increment properties associated with any element. If an instance of that named counter does not already exist in the current document nesting level, the CSS2-conscious browser automatically creates it. Thereafter, set or reset the value of the counter as needed. For example, suppose we want to use <h1> elements as chapter headings, with <h2> elements as section headings. Both chapters and sections are numbered, with section headings being reset with each new chapter. You can achieve this with:

h1:before { counter-increment : chapter; counter-reset : section }
h2:before { counter-increment : section }

When the CSS2-conscious browser encounters the first <h1> element in the document, it creates both the chapter and section counters and resets their values to 0. At the same time, and for every encounter thereafter, the CSS2-conscious browser enacts the counter-increment property to set the chapter counter to 1, representing Chapter 1, then 2, and so on. As <h2> elements are encountered within a chapter, the section counter gets incremented according to the h2 style rule, numbering each section in order. Notice, too, that the section counter gets reset by the h1 rule so that the section counter restarts for each chapter.[*]

[*] Note here that the browser doesn't display counters unless you explicitly tell it to. See "Using counters in your documents."

Both the counter-reset and counter-increment properties accept lists of counter names, letting you reset or increment groups of counters in one property. You can also supply a numeric value after a counter name so that with counter-reset, the counter gets initialized to that specified value, and counter-increment adds the value to the current counter value. Negative numbers are allowed, too, so that you may count down, if desired.

For example, if we want our document to begin with Chapter 7 and we want section numbers to increase by 2, we might rewrite the previous example as follows:

body { counter-reset : chapter 6 }
h1:before { counter-increment : chapter; counter-reset : section }
h2:before { counter-increment : section 2 }

Notice how we created the chapter counter in the earliest possible element in our document, using a value one less than the desired first value. When the browser encounters the first <h1> element, it creates, sets to 6, and then increments the chapter counter.

The scope of a counter name is the nesting level in which it is defined; it is not necessarily document-wide. If you use the same counter name in a child element, the browser creates a new instance of the counter at that level. In our example, all the <h1> and <h2> elements exist at the same nesting level, so one instance of the chapter and section counters serves that whole level. If you nested a <div> tag in that element, which in turn contained <h1> and <h2> elements, new instances of both counters would be created at that new level.

This nesting behavior is critical for nested numbered lists to work. If you associate a counter with the <li> element and then nest several ordered lists, each list level has its own instance of the counter, with separate number sequences at each level.

Using counters in your documents

Creating counters is of little use if you don't display their values in your documents. The display is not automatic. To show a counter, use the special counter( ) and counters( ) values in the content property.

The counter( ) value requires the name of a counter inside its parentheses, with an optional format specification. The browser then displays the value of the specified counter within the generated content in the format desired. The format can be any list format accepted by the list-style-type property, as described earlier in section

For example, to actually display the numbers of our numbered chapters and sections, we expand our style rules for the <h1> and <h2> elements:

h1:before { counter-increment : chapter;
   counter-reset : section;
   content : "Chapter " counter(chapter) ": " }
h2:before { counter-increment : section;
   content : "Section " counter(section) ": "}

Then, when the CSS2-conscious browser encounters this in the document:

<h1>Kumquat Growers</h1>

it renders it as shown in Figure. To number our chapters using Roman numerals, we would change the properties to:

h1:before { counter-increment : chapter;
   counter-reset : section;
   content : "Chapter " counter(chapter, upper-roman) ": " }
h2:before { counter-increment : section;
   content : "Section " counter(section, lower-roman) ": "}

The counter( ) value is the value of the counter at the current nesting level. To access all the values of the same-named counter at all nesting levels, use the plural counters( ) value instead. Include the counter name in the parentheses and a separator string. The browser puts the separator string between each list of values for the counter in the display. You may also supply a format type to switch from the default decimal numbering.

Use CSS2 counters to automatically number chapters and sections

The counters( ) value is most useful when creating nested numbered lists. Consider these properties:

ol { counter-reset: item }
li:before { counter-increment: item ;
   content: counters(item, ".") }

If you nest several <ol> elements in your document, each <li> includes all the nested values, separated by periods. This should create the familiar numbering pattern[*] of 1, 1.1, 1.1.1, and so on, as the nesting increases, as we demonstrated much earlier in this chapter (refer to Figure).

[*] Surely you've noticed it in this book!

Again, only the newcomers Firefox and Opera properly display styles-generated counters and content.

Creating markers

According to the CSS2 standard, the browser should place styles-generated content before or after the conventional HTML/XHTML content of the affected element, and it should therefore become part of the element's flow. This is not acceptable for numbered lists, where the number should be displayed separate from the content of each numbered item. To do this, add the display property to your generated content, with the special value of marker. To make our nested numbered list example completely correct, for instance, we use the rules:

ul { counter-reset: item }
li:before { display : marker;
   counter-increment: item ;
   content: counters(item, ".") }

This way, the generated counter number gets rendered to the left of the element's actual content. In a similar fashion, you can place markers after an element. For example, use the following properties to create numbered equations within chapters (the <blockquote> element delineates the equation):

h1:before { counter-increment : chapter;
   counter-reset : equation }
blockquote:after { counter-increment : equation;
   display : marker;
   content : "("counter(chapter, upper-roman) "-" counter(equation) ")" }

When rendering a marker, the browser determines where to place the marker content in relation to the element's actual content. You modify this behavior with the marker-offset property. It accepts a numerical (length) value equal to the distance between the edge of the marker and the edge of the associated element. For example, to ensure that our equation numbers get shifted 0.5 inches away from the related equation, we could use:

h1:before { counter-increment : chapter;
   counter-reset : equation }
blockquote:after { counter-increment : equation;
   display : marker;
   content : "("counter(chapter, upper-roman) "-" counter(equation) ")";
   marker-offset : 0.5in }

Audio Properties

From its humble beginnings, HTML has been a visual medium for computer display devices. Although increasing attention has been paid to other media as the standard evolved, CSS2 is the first real effort to comprehensively address using HTML/XHTML documents for nonvisual media.

For example, CSS2 forecasts that someday some browsers will be able to speak the textual content of a document, using some sort of text-to-speech technology. Such a browser would be of enormous help for the visually impaired and would also allow web browsing via the phone and other devices where a visual display is not readily available or usable. Imagine the excitement of driving down the road while your favorite web pages are read to you![*]

[*] Conversely, imagine the annoyance of someone having web pages read to them while you try to enjoy a quiet meal or watch a movie. We are constantly reminded that every advance in technology has a dark side.

CSS2 attempts to standardize these alternative renderings by defining a number of properties that control the aural experience of a web listener. None of them is currently supported in any popular browser, but we envision a time in the near future when you may be able to take advantage of some or all of these properties.

The volume property

The most basic aural property is volume. It accepts numeric length or percentage values along with a few keywords corresponding to preset volume levels.

Numeric values range from 0 to 100, with 0 corresponding to the minimum audible level and 100 being the maximum comfortable level. Note that 0 is not the same as silent, as the minimum audible level in an environment with loud background noise (like a factory floor) may be quite high.

Percentage values compute an element's volume as a percentage of the containing element's volume. Computed values less than 0 are set to 0; values greater than 100 are set to 100. Thus, to make an element twice as loud as its parent element, set the volume property to 200%. If the volume of the parent element is 75, the child element's volume gets set to the limit of 100.

You also may specify a keyword value for the volume property. Here, silent actually turns the sound off. The x-soft value corresponds to a value of 0; soft is the same as the numeric volume of 25; medium is 50, loud is 75, and x-loud corresponds to 100.

Speaking properties

Three properties control whether and how text is converted to speech. The first is speak, which turns speech on and off. By default, the value of speak is normal, meaning that text is converted to speech using standard, locale-specific rules for pronunciation, grammar, and inflection. If you set speak to none, speech is turned off. You might use this feature to suppress speaking of secondary content or content that does not readily translate to audio, such as a table.

Finally, you can set the speak property to spell-out, which spells out each word. This is useful for acronyms and abbreviations. For example, using:

acronym { speak : spell-out }

ensures that acronyms such as URL get translated aurally as "you-are-ell" and not as "earl."

By default, the speak-punctuation property is set to none, causing punctuation to be expressed as pauses and inflection in the generated speech. If you give this property the code value, punctuation is spoken literally. This might be useful for aurally reproducing programming code fragments or literal transcriptions of some content.[*]

[*] Regrettably, there is no victor-borge mode for this property. Perhaps CSS3 will address this egregious oversight.

The speak-numeral property defaults to the value continuous, meaning that numerals are pronounced as a single number. Accordingly, the number "1234" would be reproduced as "one thousand two hundred thirty-four." When set to digits, the numbers are pronounced digit by digit, such as "one, two, three, four."

Voice characteristics

To create a richer listening experience, CSS2 defines a number of properties that alter the spoken content. This lets you use different voices for different content, speed up the speech, and change the pitch and stress levels in the speech.

The speech-rate property accepts a numeric length value that defines the number of words spoken per minute. The default value is locale dependent because different cultures have different notions of a "normal" rate of speech. Instead of a specific value, you may use any of the keywords x-slow, slow, medium, fast, and x-fast, corresponding to 80, 120, 180, 300, and 500 words per minute, respectively. The faster keyword sets the rate to 40 words per minute faster than the containing element, and slower sets the rate to 40 words per minute slower than the containing element.

The voice-family property is the aural analog of the font-family property. A voice family defines a style and type of speech. Such definitions are browser and platform specific, much like fonts. It is assumed that browsers will define generic voice families, such as "male," "female," and "child," and may also offer specific voice families like "television announcer" or "book author." The value of the voice-family property is a comma-separated list of these voice family names; the browser goes down the list until it finds a voice family that it can use to speak the element's text.

The pitch property controls the average pitch, with units in hertz (hz), of the spoken content. The basic pitch of a voice is defined by the voice family. Altering the pitch lets you create a variation of the basic voice, much like changing the point size of a font. For example, with a change in pitch, the "book author" might be made to sound like a chipmunk.[*]

[*] Assuming, of course, that she doesn't already sound like a chipmunk.

You can set the pitch property to a numeric value such as 120hz or 210hz (the average pitches of typical male and female voices) or to one of the keywords x-low, low, medium, high, or x-high. Unlike other speech property keywords, these do not correspond to specific pitch frequencies but instead depend on the base pitch of the voice family. The only requirement is that these keywords correspond to increasingly lower or higher pitches.

While the pitch property sets the average pitch, the pitch-range property defines how far the pitch can change as the browser reproduces text aurally. The value of this property is a numeric value ranging from 0 to 100, with a default value of 50. Setting the pitch-range to 0 produces a flat, monotonic voice; values over 50 produce increasingly animated and excited-sounding voices.

The stress property controls the amount of inflection that is placed on elements in the spoken text. Various languages have differing rules for stressing syllables and adding inflection based on grammar and pronunciation rules. The stress property accepts a value in the range of 0 to 100, with the default value of 50 corresponding to "normal" stress. Using a value of 0 eliminates inflection in the spoken content. Values over 50 increasingly exaggerate the inflection of certain spoken elements.

The richness property controls the quality or fullness of the voice. A richer voice tends to fill a room and carries farther than a less rich, or smoother, voice. Like pitch and stress, the richness property accepts a numeric value in the range of 0 to 100, with a default value of 50. Values approaching 0 make the voice softer. Values over 50 make the voice fuller and more booming.

Pause properties

Like whitespace in a printed document, insert pauses in spoken content to offset and thereby draw attention to content as well as to create a better-paced, more understandable spoken presentation.

The pause-before and pause-after properties generate pauses just before or just after an element's spoken content. These properties accept either an absolute time value (using the s or ms unit) or a percentage value. With a percentage value, the pause is relative to the length of time required to speak a single word. For example, if the speech rate is 120 words per minute, one word, on average, is spoken every 0.5 seconds. A pause of 100 percent, therefore, would be 0.5 seconds long; a 20 percent pause would be 0.1 seconds long, and so on.

The pause property sets both the pause-before and pause-after properties at once. Use one value for pause to set both properties; the first of two values sets pause-before, and the second sets the pause-after property value.

Cue properties

Cue properties let you insert audible cues before or after an element. For example, you might precede each chapter in a book with a musical cue, or denote the end of quoted text with an audible tone.

The cue-before and cue-after properties take as their value the URL of a sound file, which the browser loads and plays before or after the styled document element, respectively. Technically, the sound can be of any duration, but the presumption is that audible cues are short and nonintrusive, enhancing the audio experience instead of overwhelming it.

Use the cue property to set both the cue-before and cue-after properties at once. If you provide one URL value, it sets both cue sounds; with two values, the first sets the cue-before sound and the second sets the cue-after sound.

Audio mixing

To create a more pleasant listening experience, you may want to play background music during a spoken passage. The play-during property meets this need. Its values are the URL of the sound file and several keywords that control playback.

The repeat keyword repeats the background audio until the spoken content is complete. If you don't use this keyword, the background sound plays once, even if it is shorter than the spoken content. A background sound that is longer than the spoken content ends when the content ends.

The mix keyword tells the CSS2-conscious browser to meld the background sound with any other background sounds that may be playing as defined by some parent element. If you don't use this keyword, child-element background sounds replace parent-element background sounds, which resume when the current element has finished.

In lieu of a URL representing the background sound, you can use the value none. This lets you silence all background sounds, such as one or more playing from parent elements, while the current element is being spoken.

Spatial positioning

While a rendered document exists on a two-dimensional page, spoken content can be placed anywhere in the three-dimensional space surrounding the listener. The CSS2 standard defines the azimuth and elevation properties so that you can place spoken content from elements in different places around the listener. azimuth relates to where and elevation tells how far above or below the sound appears to the listener.

The azimuth property accepts either an angle value or keywords indicating a position around the listener. The position directly in front of the listener is defined to be 0 degrees. The listener's right is at 90 degrees, and directly behind is 180 degrees. The listener's left is at 270 degrees or, equivalently, -90 degrees.

Position keywords include a base position, possibly modified by the behind keyword. These keywords correspond to the angular positions listed in Figure.

Angular equivalents for azimuth keywords


Angular position

Angular position when used with behind




























The leftwards keyword subtracts 20 degrees from the parent element's azimuth. Similarly, rightwards adds 20 degrees to the parent element's azimuth. Note that this process can continue until you work your way around the listener; these values add or subtract 20 degrees no matter what the azimuth of the parent is.

The elevation property accepts an angular value ranging from -90 degrees to 90 degrees, corresponding to from directly below the listener to directly above the listener. Zero degrees is considered to be level with the listener's ears. You can also use the below, level, and above keywords for -90, 0, and 90 degrees, respectively.

Use the higher keyword to increase the elevation by 10 degrees over the parent element's elevation; lower changes the elevation of the sound to 10 degrees below the parent element's elevation.

Paged Media

Printing has never been HTML's strong suit. In fact, the HTML and XHTML standards have intentionally ignored printing because printing assumes page layout, and HTML and XHTML are not layout tools.

Authors use cascading stylesheets to format and lay out their HTML/XHTML document contents, so it is not surprising that the CSS2 standard introduces some basic pagination control features that let authors help the browser figure out how to best print their documents. These features fall into two groups: those that define a particular page layout and those that control the pagination of a document.

Defining pages

As an extension to the box model, CSS2 defines a page box, a box of finite dimensions in which content is rendered. The page box does not necessarily correspond to a physical sheet of paper; the user agent maps one or more page boxes to sheets of paper during the printing process. Many small page boxes may fit on a single sheet; large page boxes may be scaled to fit on a sheet or may be broken across several sheets at the discretion of the browser.

During the printing process, content flows into the page box, is paginated appropriately, and is transferred to a target sheet on a hard-copy output device. The dimensions of the page box may differ from the browser's display window, so the flow and rendering of a printed document may be completely different from its onscreen representation. As always, obtaining a specific rendered appearance for your documents is generally impossible. However, you can use the CSS2 pagination features to help the browser print your document in an attractive, useful manner.

You define a page box using the special @page at-rule. Immediately following the @page keyword is an optional name for the page, followed by a list of properties separated by semicolons and enclosed in curly braces. These properties define the size, margins, and appearance of the page box.

Use the size property to specify the size of the page box. The value of this property is either one or two length values, or one of the special keywords portrait, landscape, or auto. If you provide a single length value, it creates a square, setting both the width and the height of the page to that value. Two length values set the width and the height of the page, respectively. The portrait keyword specifies the locally accepted page size that is taller than it is wide (typically 8 x 11), and landscape uses a locally accepted page size that is wider than it is tall (typically 11 x 8 inches). Finally, auto creates a page box that is the same size as the target sheet of paper on which the document is printed.

In general, you should use the special page size keywords to ensure that your document prints well in the local environment. Using:

@page normal { size : 8.5in 11in }

works fine in the U.S. but may fail in European locales. Instead, use:

@page normal { size : portrait }

which should select an 8.5" x 11" page in the U.S. and an A4 sheet in Europe.[*]

[*] The word normal in the rule is the page name, of course.

Use the margin, margin-top, margin-bottom, margin-left, and margin-right properties within the @page at-rule to set margins for your page. Keep in mind that the browser may define margins for rendering the page box within the target sheet, so your margins are in addition to those margins. The default margins for the page box are not defined and are browser dependent.

Finally, the marks property is used within the @page at-rule to create crop and registration marks outside the page box on the target sheet. By default, no marks are printed. You may use one or both of the crop and cross keywords to create crop marks and registration marks, respectively, on the target print page.

Left, right, and first pages

In many printing applications, authors want different page layouts for the first page of their document as well as differing formats for right and left pages in double-sided documents. CSS2 accommodates all of these cases using three pseudoclasses attached to the name of a page.

The :first pseudoclass applies the page format to the first page in a document. Page-layout attributes specified in the :first page override corresponding attributes in the general page layout. You can use the :first pseudoclass in conjunction with a named page layout; the appropriate first-page layout is applied if the first page of the document is rendered using the named page.

In a similar fashion, the :left and :right pseudoclasses define left and right page layouts for your document. Again, named pages can have left and right variations. The browser automatically applies appropriate left and right layouts to every page in the document, if such layouts exist.

You need not specify named pages to use any of these pseudoclasses. Indeed, most documents do not do so. For example, if you use these settings:

@page :first { margin-top : 3in }
@page :left { margin-left : 2in; margin-right : 1in }
@page :right { margin-left : 1in; margin-right : 2in }

without further intervention, the first page of your document will have a 3-inch top margin (and an appropriate right and left margin, depending on how your locale defines whether the first page of a document is on the right or the left). Subsequent pages will alternate between wide and narrow inner and outer margins.

Using named pages

Once you create a named page layout, you can use it in your document by adding the page property to a style that is later applied to an element in your document. If an element has a page layout that is different from that of the preceding or containing element, a page break is inserted into the document, and formatting resumes using the new page layout. When the scope of the element ends, the page layout reverts to the previous layout, with appropriate page breaks as needed.

For example, this style renders all the tables in your document on landscape pages:

@page { size : portrait }
@page rotated { size : landscape }
table { page : rotated }

While printing, if the browser encounters a <table> element in your document and the current page layout is the default portrait layout, it starts a new page and prints the table on a landscape page. If nontabular content follows the table, the browser inserts another page break, and the flow resumes on the default portrait-size page. Several tables in a row would be rendered on a single landscape sheet, if they all fit.

Controlling pagination

Unless you specify otherwise, page breaks occur only when the page format changes or when the content overflows the current page box. To otherwise force or suppress page breaks, use the page-break-before, page-break-after, and page-break-inside properties.

Both the page-break-before and page-break-after properties accept the auto, always, avoid, left, and right keywords. auto is the default; it lets the browser generate page breaks as needed. The keyword always forces a page break before or after the element, and avoid suppresses a page break immediately before or after the element. The left and right keywords force one or two page breaks so that the element is rendered on a lefthand or righthand page.

Using pagination properties is straightforward. Suppose your document has level-1 headers start new chapters, with sections denoted by level-2 headers. You'd like each chapter to start on a new, righthand page, but you don't want section headers to be split across a page break from the subsequent content. Accordingly, you might write your CSS2 print rule as follows:

h1 { page-break-before : right }
h2 { page-break-after : avoid }

Use only the auto and avoid values with the page-break-inside property. auto allows page breaks within the element (the default behavior), and avoid suppresses them. Even so, elements that are larger than the printed page get broken up; that is why the keyword is avoid and not prevent.

If you prefer that your tables not be broken across pages if possible, you would write the following rule:

table { page-break-inside : avoid }

Controlling widows and orphans

In typographic lingo, orphans are those lines of a paragraph stranded at the bottom of a page due to a page break, and widows are those lines remaining at the top of a page following a page break. Generally, printed pages do not look attractive with single lines of text stranded at the top or bottom. Most printers try to leave at least two or more lines of text at the top or bottom of each page.

If you want to take control of this behavior, you can apply the widows and orphans properties to an element. The value of each property is the minimum number of lines of text that can be left at the top or bottom of the page, respectively. The default is 2, meaning that the browser generates page breaks as needed to ensure that at least two lines of text from the element appear at the top or bottom of each page. You generally want to apply this property to all of the elements in your document, to ensure consistent pagination throughout.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows