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.

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}
-->
</style>

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.[53] 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 ...

Get HTML & XHTML: The Definitive Guide, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.