Use Cascading Style Sheets Selectors
By Nicholas Chase2004-06-18
Class selectors
After type selectors, the most commonly used selectors are class selectors. A class selector selects all elements that have a class attribute with a particular value. Preceding the name of the class with a period (.) signals to the browser that this is a class selector. For example, the following code in Listing 4 bolds any text that is in the category class:
Listing 4. Using a class selector
...
<style type="text/css">
* { font-family: Verdana }
td { font-size: 10pt }
.category { font-weight: bold; }
</style>
...
Classes are an excellent way to increase the maintainability of Web pages, because wholesale changes can be made to the look and feel of a site with just a change to the stylesheet. Classes make it possible to discriminate based on logical or business criteria, rather than simply by an accident of layout. For example, you might create a class that allows you to set all person names to a particular style.
In some cases, you might find it useful to further restrict a class-based rule based on the element to which the class is attached. You can accomplish this task by appending the class name to the element name. For example, category names within a table data cell can be set to italics as shown in Listing 5.
Listing 5. Restricting a class based on element
...
<style type="text/css">
* { font-family: Verdana }
td { font-size: 10pt }
.category { font-weight: bold; }
td.category { font-style: italic }
</style>
...
Because the text "Best In Show" is outside a table data element, the new rule doesn't apply, as shown in Figure 4.
Figure 4. Using class selectors
Tutorial Pages:
» The basic page and the universal selector
» Type selectors
» Class selectors
» ID selectors
» Family relationships: descendants, children, and siblings
» Pseudo-classes and pseudo-elements
» Summary
First published by IBM developerWorks
