Producing web pages
* HTML CSS DHTML XHTML A to Z of tags        Accessibility          Design

Using the class attribute as a selector

If you set up a style for a tag, it applies every time you usethe tag. For example, this style makes every <h1> tag in your document 14pt and black:

h1 {font: 14pt; color: black;}

If you want more control, use classes to create different styles for a single HTML tag. For example, if you want to use three colours for your <h1> headings, you define three classes in your <style> tag:

h1.red   {font: 15pt/17pt; color: red;}
h1.green {font: 15pt/17pt; color: green;}
h1.blue  {font: 15pt/17pt; color: blue;}

If you use them like this…

Your page looks like…

<h1 class="red">This is the red heading</h1>
...
<h1 class="blue">This is the blue heading</h1>
...
<h1 class="green">You get the picture...</h1>

You can also set up classes that you can use with more than one tag. You may see this called a generic class. For example:

.center  {text-align: center;}

You can then apply this class to any tag:

<p class="center">
<h1 class="center">

Choose a naming scheme for classes that makes sense. It is better to name the class by function rather than appearance, For example:

.warning {color: red; font-weight: bold; 
               text-decoration: underline;}

The style rule applied to class warning turns text red, bold, and underlined. In this case, you can change the style declaration, for example the colour, and the class name still makes sense.

In CSS2, you can set more than one class for a tag.