Section 8.3. Style Classes

CSS2 classes allow you to create several different styles for the same element, at the document level or in an external style sheet. Later in a document, you explicitly select which style to apply to that particular instance of the tag by including the style-related class attribute with the name value of one of the previously defined styles.

8.3.1 Regular Classes

In a technical paper, you might want to define one paragraph style for the abstract, another for equations, and a third for centered quotations. Differentiate these paragraphs by defining each as a different style class:

<style type="text/css">


p.abstract {font-style: italic; 

            margin-left: 0.5cm; 

            margin-right: 0.5cm}

p.equation {font-family: Symbol; 

            text-align: center}

h1, p.centered {text-align: center; 

                margin-left: 0.5cm; 

                margin-right: 0.5cm}



Notice first in the example that defining a class is simply a matter of appending a period-separated class name as a suffix to the tag name as the selector in a style rule. Unlike the XHTML-compliant selector, which is the name of the standard tag and must be in lowercase, the class name can be any sequence of letters, numbers, and hyphens, but it must begin with a letter.[6] Careful, though: case does matter, so abstract is not the same as AbsTRact. Classes, like selectors, may be included with other selectors, separated by commas, as in the third example. The only restriction on classes is that they cannot be nested; for example, p.equation.centered is not allowed.

[6] Due to its support of JavaScript style sheets, Netscape 4 cannot handle class names that happen to match JavaScript keywords. The class "abstract," for instance, generates an error in Netscape 4.

Accordingly, the first rule in the example creates a class of paragraph styles named abstract whose text is italic and indented from the left and right margins by 0.5 centimeters. Similarly, the second paragraph style class, equation, instructs the browser to center the text and to use the Symbol typeface to display the text. The last style rule creates a style with centered text and 0.5-centimeter margins, applying this style to all level-1 headers as well as creating a class of the <p> tag named centered with that style.

To use a particular class of a tag, you add the class attribute to the tag, as in this example (rendered by Internet Explorer in Figure 8-3):

<p class=abstract>

This is the abstract paragraph.  See how the margins are indented?


<h3>The equation paragraph follows</h3>

<p class=equation>

a = b + 1


<p class=centered>

This paragraph's text should be centered.

Figure 8-3. Use classes to distinguish different styles for the same tag

For each paragraph, the value of the class attribute is the name of the class to be used for that tag.

8.3.2 Generic Classes

You may also define a class without associating it with a particular tag and apply that class selectively through your documents for a variety of tags. For example:

.italic {font-style: italic}

creates a generic class named italic. To use it, simply include its name with the class attribute. So, for instance, use <p class=italic> or <h1 class=italic> to create an italic paragraph or header.

Generic classes are quite handy and make it easy to apply a particular style to a broad range of tags. Netscape and Internet Explorer support CSS2 generic classes.

8.3.3 ID Classes

Almost all HTML tags accept the id attribute, which assigns to the element an identifier that is unique within the document. This identifier can be the target of a URL, used by automated document-processing tools, and can also be used to specify a style rule for the element.

To create a style class that the styles-conscious browser applies to only those contents of your document explicitly tagged with the id attribute, follow the same syntax as for style classes, except with a # character before the class name instead of a period. For example:



#yellow {color : yellow}

h1#blue {color : blue}



Within your document, use that same id name to apply the style, such as <h1 id=blue> to create a blue heading. Or, as in the example, use id=yellow elsewhere in the document to turn a tag's contents yellow. You can mix and match both class and id attributes, giving you a limited ability to apply two independent style rules to a single element.

There is a dramatic drawback to using style classes this way: the HTML and XHTML standards dictate that the value of the id attribute be unique for each instance in which it's used within the document. Yet here, we have to use the same value to apply the style class more than once.

Even though current browsers let you get away with it, we strongly discourage creating and using the id kinds of style classes. Stick to the standard style class convention to create correct, robust documents.

8.3.4 Pseudoclasses

In addition to conventional style classes, the CSS2 standard defines pseudoclasses, which allow you to define the display style for certain tag states, such as changing the display style when a user selects a hyperlink. You create pseudoclasses like regular classes, but with two notable differences: they are attached to the tag name with a colon instead of a period, and they have predefined names, not arbitrary ones you may give them. There are seven pseudoclasses, three of which are explicitly associated with the <a> tag. Hyperlink pseudoclasses

CSS2-compliant browsers distinguish three special states for the hyperlinks created by the <a> tag: not yet visited, currently being visited, and already visited. The browser may change the appearance of the tag's contents to indicate its state, such as with underlining or color. Through pseudoclasses, you can control how these states get displayed by defining styles for a:link (not visited), a:active (being visited), and a:visited.

The :link pseudoclass controls the appearance of links that are not selected by the user and have not yet been visited. The :active pseudoclass defines the appearance of links that are currently selected by the user and are being processed by the browser. The :visited pseudoclass defines those links that the user has already visited.

To completely define all three states of the <a> tag, you might write:

a:link {color: blue}

a:active {color: red; font-weight: bold}

a:visited {color: green}

In this example, the styles-conscious browser is supposed to render unvisited links in blue. When the user selects a link, the browser should change its text color to red and make it bold. Once visited, the link reverts to conventional green text. Interaction pseudoclasses

The CSS2 standard defines two new pseudoclasses that, along with :active, relate to user actions and advise the interactive agent, such as a browser, how to display the affected element as the user interacts with the element. In other words, these two pseudoclasses ? hover and focus ? are dynamic.

For instance, when you drag the mouse over a hyperlink in your document, the browser may change the mouse-pointer icon. Hovering can be associated with a style that is in effect only while the mouse is over the element. For example, if you add the :hover pseudoclass to our example list of hyperlink style rules:

a:hover {color: yellow}

the text associated with unvisited links normally is rendered in blue but turns yellow when you point to it with the mouse, red while you visit it, and green after you're done visiting.

Similarly, the :focus pseudoclass lets you change the style for an element when it becomes the object of attention. An element may be under focus when you tab to it, click on it, or, depending on the browser, advance the cursor to it. Regardless of how the focus got to the element, the style rules associated with the focus pseudoclass are applied only while the element has the focus. Nesting and language pseudoclasses

The CSS2 :first-child pseudoclass lets you specify how an element may be rendered when it is the first instance, a.k.a. "child," of the containing element. For instance, the following rule gets applied to a paragraph when it is the first element of a division; there can be no intervening elements (notice the special greater-than bracket syntax relating the first child with its parent element):

div > p:first-child  {font-style: italic}

Accordingly, the first paragraph in the following HTML fragment would be rendered in italics by a CSS2-compliant browser because it is the first child element of its division. Conversely, the second paragraph comes after a level-2 header, which is the first child of the second division. So, that second paragraph in the example gets rendered in plain text, because it is not the first child of its division:



    I get to be in italics.




  <h2> New Division</h2>


    I'm in plain text because my paragraph is a second child of the division.

Finally, the CSS2 standard defines a new pseudoclass that lets you select an element based on its language. For instance, you might include the lang=fr attribute in a <div> tag to instruct the browser that the division contains French language text. The browser may specially treat the text. Or, you may impose a specific style with the pseudoclass :lang . For example:

div:lang(it) {font-family: Roman}

says that text in divisions of a document that contain the Italian language should use the Roman font family. Appropriate, don't you think? Notice that you specify the language in parentheses immediately after the lang keyword. Use the same two-letter ISO standard code for the pseudoclass :lang as you do for the lang attribute. [Section] Browser support of pseudoclasses

None of the popular browsers support the :lang, :first-child, or :focus pseudoclasses yet. All the current popular browsers support the :link, :active, :hover, and :visited pseudoclasses for the hyperlink tag (<a>). Even though :active also may be used for other elements, none of the browsers yet support applications beyond the <a> tag.

8.3.5 Mixing Classes

You can mix pseudoclasses with regular classes by appending the pseudoclass name to the selector's class name. For example, here are some rules that define plain, normal, and fancy anchors:

a.plain:link, a.plain:active, a.plain:visited {color: blue}

a:link {color: blue}

a:visited {color: green}

a:active {color: red}

a.fancy:link {font-style: italic}

a.fancy:visited {font-style: normal}

a.fancy:active {font-weight: bold; font-size: 150%}

The plain version of <a> is always blue, no matter what the state of the link is. Accordingly, normal links start out blue, turn red when active, and convert to green when visited. The fancy link inherits the color scheme of the normal <a> tag but adds italic text for unvisited links, converts back to normal text after being visited, and actually grows 50% in size and becomes bold when active.

A word of warning about that last property of the fancy class: specifying a font-size change for a transient display property results in lots of browser redisplay activity when the user clicks on the link. Given that some browsers run on slow machines, this redisplay may be annoying to your readers. Given also that implementing that sort of display change is something of a pain, it is unlikely that most browsers will support radical appearance changes in <a> tag pseudoclasses.

8.3.6 Class Inheritance

Classes inherit the style properties of their generic base tags. For instance, all the properties of the plain <p> tag apply to a specially defined paragraph class, except where the class overrides a particular property.

Classes cannot inherit from other classes, only from the unclassed versions of the tags they represent. In general, therefore, you should put as many common styles as possible into the rule for the basic version of a tag and create classes only for those properties that are unique to that class. This makes maintenance and sharing of your style classes easier, especially for large document collections.