10.3 Classes

CSS really comes into its own with the class selector. The class selector allows you to define different styles for the same HTML element. The class selector is defined using a full-stop "." after the usual selector, e.g.:

p.caution {color: red}
p.important {font-weight: bold}
p.neat {text-align: justify}
Note that you can call the classes anything you like. To apply the class(es) to an actual paragraph you use the HTML class attribute:
<p class=caution>

You can apply multiple classes to a single element via:
<p class="caution important neat">

This is what the styles look like:

This is a paragraph using the caution class.

This is a paragraph using the important class.

This is a paragraph using both the important class and the neat class. Notice the beautifully straight edges to this paragraph that comes from the text justification. This paragraph will always be nice and neat like this, even if you shrink the size of the window. Of course this neatness does not detract from its importance, emphasised by its emboldened text.

Sometimes you might want to define a class for every element, and to do this you just omit the HTML element from the selector, e.g.
.caution {color: red}
.centre {text-align: center}

Span and Div

Sometimes we might want to apply a class to a region of text that isn't actually a separate element. We can do that using the <span>...</span> tags for a short section, or the <div>...</div> tags for a large (multi-line) section.

CSS Comments

It is important to comment your CSS files as well, especially as they grow. CSS comments use a C-like syntax, with the comment sandwiched between /* and */:
/* This is a CSS comment */


Some HTML elements are not quite as straightforward to set as others. For example, what should be do with the anchor element that we use for links? Setting its colour to red is all well and good, but we probably want that colour to change depending on whether we've visited that link or not.

The answer to this conundrum is that we use pseudo-classes. Pseudoclasses come after the separator and class name, and are separated from them by a colon, e.g.:

a:link {color: blue}         /* Colour all links blue by default */
a.blue:visited {color: navy} /* If a link of class "blue" has been visited, colour it navy */ 

Annoyingly, the order of these pseudo-class definitions does matter sometimes:

a.red:link {color: #FF0000}   
a.red:visited {color: maroon} 
a.red:hover {font-style: italic} /* what happens when the mouse hovers over it. It must come after "link" and "visited" */ 
a.red:active {color: silver}     /* what happens when clicked. It must come after "hover" */ 

Exercise 9

Rewrite your home page to use CSS files. You might like to base it on this CSS file.

Previous page Next page