Dynamic styles are an integral component of interactive Web pages. The document's appearance is defined using style sheets and HTML. Dynamic styles use the object model to modify the document's CSS (Cascading Style Sheets) in order to change the appearance of the document. The syntax for declaring a CSS was introduced in Chapter 1, "Overview of CSS and HTML" This chapter focuses on modifying style sheets using scripts in order to alter the document's appearance.
By applying dynamic styles to documents, existing documents can be transformed into more exciting documents without a loss of contents on down-level browsers. On a down-level browser, the document appears static, but when Dynamic HTML is supported the document comes to life. Because the easiest and most effective way to learn about dynamic styles is to study and review code samples, this chapter provides a large number of plug-and-play code modules. The purpose of these examples is to demonstrate how to apply various techniques for creating more interactive documents.
The following topics are covered in this chapter:
- Dynamic styles and CSS
- Programming style sheet properties
This section describes how style sheet properties are exposed by the object model. CSS properties do not always translate easily into object model properties because a single attribute may contain many properties. For example, the background attribute contains the background color, image, and repeat information.
- Inline styles
This section shows you how to program the inline style of an element, the simplest technique for adding dynamic styles. A style property that provides access to all the CSS-related properties is exposed on every element.
- Changing the class attribute
A simple and elegant technique for creating dynamic styles is to write code that modifies the class or id attribute to associate an element with a different contextual rule. This section provides reusable examples that illustrate this technique.
- Global style sheets
The inline style and the class attribute are direct modifications of an element. The document object exposes a styleSheets collection that represents all the Style elements and linked style sheets in the document. This collection lets you modify the individual style sheets directly and thereby apply formatting to the entire document.
This chapter concludes with three sections that describe techniques for taking advantage of the features introduced throughout the chapter. The section "Adaptive Layout Techniques" shows you how to make a document change in response to the environment. "Data Display Techniques" demonstrates hiding and showing data in response to the user. "Text Animation Techniques" shows you how to change styles in response to a timer.
The samples demonstrating these techniques are included on the companion CD.