home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

Chapter 18. Cascading Style Sheets and Dynamic HTML

Cascading Style Sheets (CSS) is a standard for specifying the visual presentation[64] of HTML (or XML) documents. In theory, you use HTML markup to specify the structure of your document, resisting the temptation to use deprecated HTML tags such as <font> to specify how the document should look. Instead, you use CSS to define a style sheet that specifies how the structured elements of your document should be displayed. For example, you can use CSS to specify that the level-one headings defined by <h1> tags should be displayed in bold, sans-serif, centered, uppercase, 24-point letters.

[64]And, in the CSS2 standard, also the aural presentation.

CSS is a technology intended for use by graphic designers or anyone concerned with the precise visual display of HTML documents. It is of interest to client-side JavaScript programmers because the document object model allows the styles that are applied to the individual elements of a document to be scripted. Used together, CSS and JavaScript enable a variety of visual effects loosely referred to as Dynamic HTML (DHTML).[65]

[65]Many advanced DHTML effects also involve the event-handling techniques we'll see in Chapter 19.

The ability to script CSS styles allows you to dynamically change colors, fonts, and so on. More importantly, it allows you to set and change the position of elements and even to hide and show elements. This means that you can use DHTML techniques to create animated transitions where document content "slides in" from the right, for example, or an expanding and collapsing outline list in which the user can control the amount of information that is displayed.

This chapter begins with an overview of CSS style sheets and the use of CSS styles to specify the position and visibility of document elements. It then explains how CSS styles can be scripted using the API defined by the DOM Level 2 standard. Finally, it demonstrates the nonstandard, browser-specific APIs that can be used to achieve DHTML effects in Netscape 4 and Internet Explorer 4.

18.1. Styles and Style Sheets with CSS

Styles in CSS are specified as a semicolon-separated list of name/value attribute pairs, where each name and value are separated by colons. For example, the following style specifies bold, blue, underlined text:

font-weight: bold; color: blue; text-decoration: underline;

The CSS standard defines quite a few style attributes you can set. Table 18-1 lists all the attributes except for those used only in audio style sheets. You are not expected to understand or be familiar with all these attributes, their values, or their meanings. As you become familiar with CSS and use it in your documents and scripts, however, you may find this table a convenient quick reference. For more complete documentation on CSS, consult Cascading Style Sheets: The Definitive Guide, by Eric Meyer (O'Reilly), or Dynamic HTML: The Definitive Guide, by Danny Goodman (O'Reilly). Or read the specification itself -- you can find it at http://www.w3c.org/TR/REC-CSS2/.

The second column of Table 18-1 shows the allowed values for each style attribute. It uses the grammar used by the CSS specification. Items in fixed-width font are keywords and should appear exactly as shown. Items in italics specify a data type such as a string or a length. Note that the length type is a number followed by a units specification such as px (for pixels). See a CSS reference for details on the other types. Items that appear in italic fixed-width font represent the set of values allowed by some other CSS attribute. In addition to the values shown in the table, each style attribute may have the value "inherit", to specify that it should inherit the value from its parent.

Values separated by a | are alternatives; you must specify exactly one. Values separated by || are options; you must specify at least one, but you may specify more than one, and they can appear in any order. Square brackets [] are used for grouping values. An asterisk (*) specifies that the previous value or group may appear zero or more times, a plus sign (+) specifies that the previous value or group may appear one or more times, and a question mark (?) specifies that the previous item is optional and may appear zero or one time. Numbers within curly braces specify a number of repetitions. For example, {2} specifies that the previous item must be repeated twice, and {1,4} specifies that the previous item must appear at least once and no more than four times. (This repetition syntax may seem familiar: it is the same one used by JavaScript regular expressions, discussed in Chapter 10.)

Table 18-1. CSS style attributes and their values




[background-color ||background-image ||background-repeat || background-attachment ||background-position]


scroll | fixed


color | transparent


url( url ) | none


[ [percentage | length ]{1,2} | [ [top | center | bottom] || [left | center | right] ] ]


repeat | repeat-x | repeat-y | no-repeat


[ border-width ||border-style || color ]


collapse | separate


color{1,4} | transparent


length length?


[none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset]{1,4}

border-top border-right border-bottom border-left

[ border-top-width ||border-top-style || color ]

border-top-color border-right-color border-bottom-color border-left-color


border-top-style border-right-style border-bottom-style border-left-style

none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset

border-top-width border-right-width border-bottom-width border-left-width

thin | medium | thick | length


[thin | medium | thick | length]{1,4}


length | percentage | auto


top | bottom | left | right


none | left | right | both


[rect( [length | auto]{4} )] | auto




[ string | url( url ) | counter | attr(attribute-name) | open-quote | close-quote | no-open-quote | no-close-quote ]+


[ identifier integer? ]+ | none


[ identifier integer? ]+ | none


[ [url( url ) ,]* [ auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | text | wait | help ] ]


ltr | rtl


inline | block | list-item | run-in | compact | marker | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | none


show | hide


left | right | none


[ [ font-style || font-variant || font-weight ]? font-size [ / line-height ]? font-family ] | caption | icon | menu | message-box | small-caption | status-bar


[[ family-name | serif | sans-serif | monospace | cursive | fantasy],]+


xx-small | x-small | small | medium | large | x-large | xx-large | smaller | larger | length | percentage


number | none


normal | wider | narrower | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded


normal | italic | oblique


normal | small-caps


normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900


length | percentage | auto


length | percentage | auto


normal | length


normal | number | length | percentage


[ list-style-type || list-style-position || list-style-image ]


url( url ) | none


inside | outside


disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-alpha | lower-latin | upper-alpha | upper-latin | hebrew | armenian | georgian | cjk-ideographic | hiragana | katakana | hiragana-iroha | katakana-iroha | none


[length | percentage | auto]{1,4}

margin-topmargin-right margin-bottom margin-left

length | percentage | auto


length | auto


[ crop || cross ] | none


length | percentage | none


length | percentage | none


length | percentage


length | percentage




[ outline-color || outline-style || outline-width ]


color | invert


none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset


thin | medium | thick | length


visible | hidden | scroll | auto


[length | percentage]{1,4}

padding-top padding-right padding-bottom padding-left

length | percentage


identifier | auto


auto | always | avoid | left | right


auto | always | avoid | left | right


avoid | auto


static | relative | absolute | fixed


[string string]+ | none


length | percentage | auto


length{1,2} | auto | portrait | landscape


auto | fixed


left | right | center | justify | string


none | [ underline || overline || line-through || blink ]


length | percentage


none | [color || length length length? ,]* [color || length length length?]


capitalize | uppercase | lowercase | none


length | percentage | auto


normal | embed | bidi-override


baseline | sub | super | top | text-top | middle | bottom | text-bottom | percentage | length


visible | hidden | collapse


normal | pre | nowrap




length | percentage | auto


normal | length


auto | integer

The CSS standard allows certain style attributes that are commonly used together to be combined using special shortcut attributes. For example, the font-family, font-size, font-style, and font-weight attributes can all be set at once using a single font attribute:

font: bold italic 24pt helvetica; 

In fact, some of the attributes listed in Table 18-1 are themselves shortcuts. The margin and padding attributes are shortcuts for attributes that specify margins, padding, and borders for each of the individual sides of an element. Thus, instead of using the margin attribute, you can use margin-left, margin-right, margin-top, and margin-bottom, and similarly for padding.

18.1.1. Applying Style Rules to Document Elements

You can apply style attributes to the elements of a document in a number of ways. One way is to use them in the style attribute of an HTML tag. For example, to set the margins of an individual paragraph, you can use a tag like this:

<p style="margin-left: 1in; margin-right: 1in;">

One of the important goals of CSS is to separate document content and structure from document presentation. Specifying styles with the style attribute of individual HTML tags does not accomplish this (although it can be a useful technique for DHTML). To achieve the separation of structure from presentation, we use style sheets, which group all the style information into a single place. A CSS style sheet consists of a set of style rules. Each rule begins with a selector that specifies the document element or elements to which it applies, followed by a set of style attributes and their values within curly braces. The simplest kind of rule defines styles for one or more specific tag names. For example, the following rule sets the margins and background color for the <body> tag:

body { margin-left: 30px; margin-right: 15px; background-color: #ffffff } 

The following rule specifies that text within <h1> and <h2> headings should be centered:

h1, h2 { text-align: center; }

In the previous example, note the use of a comma to separate the tag names to which the styles are to apply. If the comma is omitted, the selector specifies a contextual rule that applies only when one tag is nested within another. For example, the following rules specify that <blockquote> tags are displayed in an italic font, but text inside an <i> tag inside a <blockquote> is displayed in plain, nonitalic text:

blockquote { font-style: italic; }
blockquote i { font-style: normal; }

Another kind of style sheet rule uses a different selector to specify a class of elements to which its styles should be applied. The class of an element is defined by the class attribute of the HTML tag. For example, the following rule specifies that any tag with the attribute class="attention" should be displayed in bold:

.attention { font-weight: bold; } 

Class selectors can be combined with tag name selectors. The following rule specifies that when a <p> tag has the class="attention" attribute, it should be displayed in red, in addition to being displayed in a bold font (as specified by the previous rule):

p.attention { color: red; }

Finally, style sheets can contain rules that apply only to individual elements that have a specified id attribute. The following rule specifies that the element with an id attribute equal to "p1" should not be shown:

#p1 { visibility: hidden; } 

We've seen the id attribute before: it is used with the DOM function getElementById( ) to return individual elements of a document. As you might imagine, this kind of element-specific style sheet rule is useful when we want to manipulate the style of an individual element. Given the previous rule, for example, a script might switch the value of the visibility attribute from hidden to visible, causing the element to dynamically appear.

18.1.3. The Cascade

Recall that the C in CSS stands for "cascading." This term indicates that the style rules that apply to any given element in a document can come from a cascade of different sources. Each web browser typically has its own default styles for all HTML elements and may allow the user to override these defaults with a user style sheet. The author of a document can define style sheets within <style> tags or in external files that are linked in or imported into other style sheets. The author may also define inline styles for individual elements with the HTML style attribute.

The CSS specification includes a complete set of rules for determining which rules from the cascade take precedence over the other rules. Briefly, however, what you need to know is that the user style sheet overrides the default browser style sheet, author style sheets override the user style sheet, and inline styles override everything. The exception to this general rule is that user style attributes whose values include the !important modifier override author styles. Within a style sheet, if more than one rule applies to an element, styles defined by the most specific rule override conflicting styles defined by less specific rules. Rules that specify an element id are the most specific. Rules that specify a class are next. Rules that specify only tag names are the least specific, but rules that specify multiple nested tag names are more specific than rules that specify only a single tag name.

18.1.5. CSS Example

Example 18-1 is an HTML file that defines and uses a style sheet. It demonstrates the previously described tag name, class, and ID-based style rules, and it also has an example of an inline style defined with the style attribute. Remember that this example is meant only as an overview of CSS syntax and capabilities. Full coverage of CSS is beyond the scope of this book.

Example 18-1. Defining and using Cascading Style Sheets

<style type="text/css">
/* Specify that headings display in blue italic text. */
h1, h2 { color: blue; font-style: italic }

 * Any element of class="WARNING" displays in big bold text with large margins
 * and a yellow background with a fat red border.
          font-weight: bold;
          font-size: 150%;
          margin: 0 1in 0 1in; /* top right bottom left */
          background-color: yellow; 
          border: solid red 8px;
          padding: 10px;       /* 10 pixels on all 4 sides */

 * Text within an h1 or h2 heading within an element with class="WARNING" 
 * should be centered, in addition to appearing in blue italics.
.WARNING h1, .WARNING h2 { text-align: center }

/* The single element with id="P23" displays in centered uppercase. */
#P23 {
      text-align: center;
      text-transform: uppercase;
<h1>Cascading Style Sheets Demo</h1>

<div class="WARNING">
This is a warning!
Notice how it grabs your attention with its bold text and bright colors.
Also notice that the heading is centered and in blue italics.

<p id="P23">
This paragraph is centered<br>
and appears in uppercase letters.<br>
<span style="text-transform: none">
Here we explicitly use an inline style to override the uppercase letters.

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.