Cascading Style Sheets


Cascading Style Sheets

CSS is a language with a set of properties for defining the appearance of a document. The CSS specification (CSS1) defines properties and a declarative language for associating those properties with elements in the document. Internet Explorer 3.0 provided initial support for CSS; this support has been expanded and improved in Internet Explorer 4.0. Understanding CSS is important for adding dynamic style to a page. (Dynamic style is the modification of the style sheet associated with the document through a script.) The W3C Web site (www.w3.org) contains the latest information about the innovations and features supported by CSS.

Style sheets are an abstraction in which the style of a document is defined separately from either the contents or the structure. There are essentially three techniques available to the Web author for adding style sheets to a document—in general, each level of complexity offers greater benefits while increasing the level of abstraction necessary. The first technique is to use an inline style sheet. Inline styles are simple: the style is defined directly on the element. The second technique is to use a global style sheet to define the style for a document at the beginning of the document. The third and most abstract and powerful technique is to use a linked style sheet to define the style separately in another document.

Inline styles are not much different from traditional HTML. With inline styles, the appearance of the document cannot be easily changed. The advantage is that the amount of markup is usually significantly reduced, and HTML can be used more appropriately to provide additional context rather than just presentation. Using a global style sheet better separates the presentation from the contents and allows the style and rendering of the document to be quickly and independently modified. Using a linked style sheet provides the greatest benefit by allowing the appearance of a set of pages or an entire Web site to be defined through a single file.

The term cascading in CSS refers to the ability to merge multiple style sheets to form a single style definition for an element or for the entire document. This feature allows the Web site's style sheet to be merged in a predictable way with the style sheet in the document, and even with an inline style.

Inline Styles

An inline style is basically a style sheet for a single instance of an element and is specified in line in the element's begin tag. The inline style sheet is defined using the STYLE attribute, and the data for the attribute is specified using the style sheet language. For example, the following code makes a paragraph's contents larger and centered on a yellow background:

<P STYLE="font-size:120%; text-align:center; background:yellow">
   This creates a yellow, centered paragraph with a larger font.

Inline styles can help you learn the style sheet language or quickly change a single instance of an element. However, inline styles are not in keeping with the true spirit of a structured document and do not work well when you are trying to change the appearance of a set of elements in a document where the presentation and contents are not completely separate. To separate the document's style from its structure, the style sheet should be specified either in the document's head or as a separate file that is linked to the document.

Global Style Sheets

The <STYLE> tag is used to add a global style sheet to a document and is usually contained within the document's header. Centralizing all the document's style in a single location makes it easy to modify how the document is rendered. The following style sheet defines the rendering for all paragraphs in a document. To change the rendering of all paragraphs, only this single entry needs to be modified. If inline styles were used, every paragraph in the document would need to be changed.

      <STYLE TYPE="text/css">
         P {font-size:120%; text-align:center; background:yellow}
      <P>All paragraphs are now larger and centered on a yellow

The TYPE attribute of the <STYLE> tag defines the language for the style sheet as a MIME type. Internet Explorer 4.0 supports only CSS and therefore parses only style sheets of type text/css. If a different type is specified that is not supported by the browser, the contents of the style block are ignored. Omitting the TYPE attribute causes the language to default to text/css. Although setting the TYPE attribute is optional, doing so is still recommended to more clearly document your source code.

A selector is used to associate a style with a particular element. In the preceding example, a simple selector was created that associated a style with all paragraphs. More powerful contextual selectors can also be defined; these selectors are introduced in the section "Defining a Style Sheet" later in this chapter.

Linked Style Sheets

A linked style sheet is a style sheet that is supplied in an external file. The advantage of using a linked style sheet is that all the rules and styles can be defined and encapsulated in a single file that can be shared across multiple pages or even across the entire Web site. With a linked style sheet, the rendering of all the paragraphs on an entire Web site can be changed through a single document. A linked style sheet can also improve performance because it is cached locally on the client, separate from the document, so each document is smaller and the style information needs to be downloaded only once.

To define a linked style sheet, the <LINK> tag is used in the head of the document:

      <LINK REL="stylesheet" TYPE="text/css" HREF="fancy.css">
      <P>This document uses the styles specified in fancy.css.</P>

The REL attribute is used to specify that the linked file is a style sheet, and the TYPE attribute specifies the style sheet MIME type. The HREF attribute is a URL pointing to the external style sheet. The contents of a linked style sheet must be only contextual rules and style definitions and must not include any HTML.

Defining a Style Sheet

You use the same syntax to create a style sheet within the document that you use to create a linked style sheet. This section introduces the components of the CSS language. The CSS language consists of selectors and presentation rules. Selectors specify the elements that are associated with a particular rule, and presentation rules specify how those elements are to be rendered.

CSS provides two types of selectors: simple and contextual. The simple selector associates an element based on its attributes or type, without regard to its contextual position within other elements. Contextual selectors are more powerful in that they can associate a rule with a particular element's containership—for example, all <EM> tags inside <P> tags.

In its most basic form, a simple selector can be created that associates a particular element, class of elements, or ID with a specific style. The following code demonstrates a number of simple selectors and their presentation rules:

<STYLE TYPE="text/css">
   /* Change all H1s to red. */
   H1 {color:red} 

   /* Make all elements with CLASS="special" boldface. */
   .special {font-weight:bold} 

   /* Give the element with ID="special" a yellow background. */
   #special {background:yellow}

   /* Give the H1 elements with CLASS="cool" wider letter spacing. */
   H1.cool {letter-spacing:2px}

Selectors can also be grouped in a comma-delimited list, which allows multiple selectors to share the same declaration:

/* Make all headers share the same rule. */
H1, H2, H3, H4, H5, H6 {color:red; background:yellow}

Contextual selectors specify a containership hierarchy with which to associate the style. The containership is specified by a space-delimited list. For example, the following code defines a rule for all EM elements contained in a P element:

P EM {color:blue}

Each selector can reference the CLASS, the ID, or the element type. Here is a more complex version of a contextual selector:

/* Any element of CLASS="cool" that is contained within an 
   LI element of CLASS="special" and further contained within 
   a UL element will get this style. */
UL LI.special .cool{font-weight:bolder; font-size:120%}

All elements of a contextual selector are case insensitive—for example, .cool is the same as .cOoL.


A pseudo-class consists of elements of a single type that meet a certain contextual criterion. For example, Anchor elements that have been visited constitute a pseudo-class named visited, and active anchors and unvisited anchors constitute the active and link pseudo-classes, respectively.

The pseudo-class is specified in a style sheet using a colon (:) as the delimiter:

A:link {color:green}
:link {color:green}

The second example omits the element name (A) because only anchors have a link pseudo-class. The pseudo-class can be used in the same manner as the class or ID specifier and is also case insensitive. CSS1 defines pseudo-elements, which are similar to pseudo-classes, for the first line and first letter in an element, but Internet Explorer 4.0 currently supports only the anchor pseudo-classes.

Cascading Order

More than one selector can refer to the same elements. CSS defines a cascading order that is used to resolve any selector and rule overlaps. The cascading order merges all the rules applicable to an element by sorting them based on their specificity. For example, a Strong element contained within an H1 element might have presentation rules defined by an H1 selector, by a STRONG selector, and by a contextual selector for Strong elements inside H1 elements. The cascading aspect of CSS defines how those three rules will be merged. In general, a rule for a more specific contextual selector overrides a less specific one, and rules defined later in the source of the style sheet or document have higher precedence.

CSS Features

This section provides a sampling of some of the interesting new features of CSS supported by Internet Explorer 4.0. Some of these features can be used to replace common layout tricks that are currently performed using tables to align contents. These features are mostly contained in supplemental working drafts and proposals, not in the core CSS1 specification.

Text Justification

Internet Explorer 4.0 provides full support for left, right, and full justification of text. Full justification is new to Internet Explorer 4.0 and allows contents to be aligned at both the left and right margins. Justification is specified using the CSS text-align property:

<P STYLE="text-align:justify">
   This paragraph is justified using the CSS text-align property.

Custom Bulleted Lists

Using the list-style property, you can override built-in bullets in lists by using custom bullets as specified by a GIF. Bullets can be specified for the list itself or for individual list items. This technique degrades well on down-level browsers, where the list will be displayed using the standard bullet rather than the custom bullet. The following code demonstrates how to replace the standard bullet:

      <TITLE>Custom Bulleted List</TITLE>
      <STYLE TYPE="text/css">
         /* Display cool.gif instead of default bullet symbol. */
         UL {list-style-image:URL(cool.gif)}
         <LI>The bullet is replaced with cool.gif.</LI>

Figure 1-7 shows a list using custom bullets.

Cascading Style Sheets

Figure 1-7. A bulleted list using custom bullets.

Creating Sidebars

Sidebars were traditionally created using tables, but with the CSS float property, tables are no longer required. Text contents can be assigned a class by using a <SPAN> or <DIV> tag, and the float property can then be set in a style rule for that class. Using the float property, you can easily create two types of sidebars:

The following code demonstrates how to create these two types of sidebars:

      <TITLE>Sidebar Example</TITLE>
      <STYLE TYPE="text/css">
         BODY {margin-left:150pt; margin-right:0pt}
         .outflow, .inflow {float:left; width:150pt; color:navy}
         .outflow {margin-left:-150pt; width:150pt}
      <H1>Sidebar Example</H1>
      <DIV CLASS="inflow">
         Notice that the text wraps around this sidebar.
      <P>This example demonstrates a sidebar that exists within the 
         flow of the document. The contents wrap around the sidebar 
         and continue below it.
      <DIV CLASS="outflow">
         This sidebar appears in the left margin of the document.
      <P>This example demonstrates how to manipulate a document's 
         margins to force a sidebar to float in the margin. By 
         adjusting the margins, you can make the sidebar overlay the
         flow of the contents.

Figure 1-8 illustrates the two types of sidebars.

Cascading Style Sheets

Figure 1-8. A sidebar with text wrapping around it, and a sidebar set in the left margin.

The visibility Property vs. the display Property

The CSS1 specification defines the display property for removing elements from the presentation of the document. The working draft on CSS positioning exposes an additional property, visibility, that allows elements to become transparent in the document's flow. You use these two properties to achieve different presentation effects in the rendering and flow of the document. Setting the visibility property to hidden causes the contents to be rendered entirely transparently. The contents are still in position in the flow, but they are not visible. Setting the display property to none causes an element to be ignored by the rendering engine, as if the element never appeared in the document.

Figure 1-9 shows the effects of the visibility and display properties. The right column shows the contents either with visibility:hidden or display:none, and the left column shows the contents fully displayed. With display:none, the contents that are not displayed take up no space in the document's flow.

Cascading Style Sheets

Figure 1-9. The effects of setting the visibility and display properties.

Controlling the Cursor

The CSS cursor property is used to customize the mouse pointer when the user moves the mouse over an element. This property is especially useful when traditional text elements have script associated with them. For example, using a traditional I-beam cursor with text that the user is supposed to click like a button will be confusing. Instead, an arrow or other relevant cursor should be used.

The following table lists the settings for the cursor property currently specified by CSS. Examples of these cursors can be found with the Chapter 1 examples on the companion CD.

autoThe browser determines which cursor to display based on the current context.
crosshairSimple crosshair cursor.
defaultUsually an arrow; the platform-dependent default cursor.
handHand cursor; used to represent a region on the screen that is clickable.
textUsually an I-beam; used to indicate editable text.
helpUsually a question mark or a balloon; indicates that help is available for the object under the cursor.
e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize Various arrow-shaped cursors; used to represent a resize operation—for example, when the user clicks on the border of a window to resize the window.
moveUsed to indicate that the element can be moved.
waitUsually a watch or an hourglass; indicates that the program is busy and the user should wait.

CSS Support for Intrinsic Controls

In Internet Explorer 4.0, the text, button, and marquee controls fully support style sheets. The Select element has limited support for style sheets. To prevent problems on earlier browser implementations, intrinsic controls do not inherit style sheets from parent elements. Instead, style rules must be associated with specific elements through their element type or their CLASS or ID attributes.

The following simple style sheet formats all Input elements in a class named text as green boldface text:

<STYLE TYPE="text/css">
   INPUT.text {color:green; font-weight:bold}
<INPUT CLASS="text" TYPE=TEXT VALUE="Green Bold Text">

Using the CLASS attribute ensures that only Input elements marked with the text class are changed. This technique requires a little redundancy between the TYPE and CLASS attributes because the selector in CSS that associates elements with styles currently does not recognize arbitrary attributes; CSS is limited to associating styles with elements based only on the CLASS or ID attribute or the element type.

Embedding Custom Fonts

Before Internet Explorer 4.0, Web authors had to use the built-in fonts of the browser or guess what fonts might be available on the system. Internet Explorer 4.0 provides the Web author with the ability to specify fonts that are downloaded with the Web page, ensuring that the page is rendered correctly. The downloadable font is specified using enhancements to the CSS syntax. The syntax for specifying a downloadable font in a style sheet is shown here:

@font-face {font-family:fontName; src:url(filename.eot)}

The fontName value is a user-defined name that is later referenced by the font-family CSS property. Here is a complete example:

<STYLE TYPE="text/css">
   @font-face {
   H1 {font-family:demoFont, Arial, sans-serif}
<H1>This text is displayed using the downloaded demoFont.</H1>

Once a new font is specified, it can be used as a valid font name for font-family. The font-family property can take a list of fonts so that if the first font could not be downloaded, the browser can try a different font or a different font family until one works. In this example, the last font specified is sans-serif, which allows the browser to use any sans serif font to render the element.

User Settings

Internet Explorer 4.0 supports the ability to create Web pages that automatically adapt to the look and feel of the user's system. A set of new color and font keywords is available for specifying the user's system settings. A demo page that displays text formatted with your system settings is included with the Chapter 1 examples on the companion CD.

Table 1-1 lists the set of new color keywords available in Internet Explorer 4.0. (Existing colors that can be specified for any CSS color attribute are not listed.) A complete list of named colors as well as a demo page that displays each of these colors can be found on the companion CD.

Table 1-2 lists the font keywords that represent the current user system settings. These values can be used only for the font property; they cannot be used with the font-family property because the font-family property is already automatically based on the user's system settings.

Color Values

activeborderActive window border color
activecaptionActive window caption color
appworkspaceBackground color of multiple document interface (MDI) applications
backgroundDesktop background color
buttonfaceFace color for buttons
buttonhighlightHighlight color for buttons
buttonshadowShadow color for buttons
buttontextText color on buttons
captiontextText color in caption, the window sizing box, and scrollbar arrow buttons
graytextGrayed (disabled) text color; set to 0 if the current display driver does not support a solid gray color
highlightColor of item(s) selected in a control
highlighttextText color of item(s) selected in a control
inactiveborderInactive window border color
inactivecaptionInactive window caption color
inactivecaptiontextText color in an inactive caption
infobackgroundBackground color for ToolTip
infotextText color for ToolTip
menuMenu background color
menutextText color in menus
scrollbarColor of scrollbar background
threeddarkshadowDark shadow color for three-dimensional display elements
threedfaceFace color for three-dimensional display elements
threedhighlightHighlight color for three-dimensional display elements
threedlightshadowLight shadow color for three-dimensional display elements
threedshadowShadow color for three-dimensional display elements
windowWindow background color
windowframeWindow frame color
windowtextText color in windows

Table 1-1. New system color keywords in Internet Explorer 4.0.

Font Values

Keyword Description
caption Font used for captioned controls (buttons, drop-down lists, and so on)
icon Font used to label icons
menu Font used in menus
messagebox Font used in dialog boxes
smallcaption Font used for labeling small controls
statusbar Font used in window status bars

Table 1-2. New system font keywords in Internet Explorer 4.0.

CSS Positioning

Internet Explorer 4.0 also supports a new CSS draft, CSS-P, that provides greater control over the positioning of elements. Combining these new extensions with scripting allows elements to be animated and moved around on the page. This feature provides the Web author with complete control over the document's layout and the ability to control the position of and relationship between elements. Chapter 12, "Dynamic Positioning," introduces the syntax for positioning elements with CSS as well as the support for scripting positioned elements.

Filters and Transition Effects

Internet Explorer 4.0 also supports a set of filters and transitions that can be associated with the HTML contents. Filters can be directly applied to text in the document. Transitions allow presentation-like effects such as dissolves and slides to be added to the document or to elements in the document. For example, you can make text shadowed or semitransparent, and you can make pages fade in or out when the user enters or exits them. This functionality is supported through the new CSS filter property.


© 2000- NIV