Skip to main content

Classes

Up to now we have used a single style associated with a single HTML tag but very often in Web page design the same tag needs different styles associated with it depending upon how its being used. Most notably here is the paragraph marker where we often have different styles of paragraph within a single document, for example a quotation paragraph. Of course we could solve our problem by using inline style requests but these would be cumbersome within a large document or large Web site. The answer is to use classes which offer more versatility in allowing you to apply different definitions to the same HTML tag element.

A class is defined by specifying the selector followed by a dot and a class name, for example p.quotation or p.body and the associated class is to be used within the Web page is specified as an attribute to the tag, for example <p class="quotation"> would select the properties and values associated with the p.quoation definition. Here are some more examples:

Rule HTML Code Presentation
p.red {font-family:Arial; color:red} <p class="red">Red text paragraph</p>

Red text paragraph

p.green {font-family:Arial; color:black} <p class="green">Green text paragraph</p>

Green text paragraph

p.blue {font-family:Arial; color:blue} <p class="blue">Blue text paragraph</p>

Blue text paragraph

If you omit the tag name in the selector then the style can be applied to other tags, for example .red {font-family:Arial; color:red} could be used with a paragraph tag [<p class="red">] or a heading [<h2 class="red">].

Note: It is important to know that once you start using a style sheet then every HTML tag element used within a document should be included in the style sheet. Even experienced Web page authors get caught-out when adding new elements to an existing Web page and the tags are not included in the style sheet and the presentation results are not what was expected.