A simple example of CSS class usage

Sep 27, 2007 16:46 GMT  ·  By

CSS (Cascading Style Sheets) could help you realize that you can define your own optimized templates or documents in a short time. You can define styles that could be used on a single document or for the entire website.

If you use an external style sheet document, you will be able to make a global change to a website or a site template, by editing a single file. As it is mentioned in another article, the general CSS synthax contains three elements: selector, property and value. The value given to the property will be called by the selector any time is needed.

If you have situations when you want to use different properties / values for the same HTML tag, you can use CSS classes. CSS classes allow you to create the style for your pages fast and easy. A class selector is denoted by a dot in front of the class name. You can define different styles for the same HTML tag, as is presented in the next example:

code
h1.style1 {font-family: Arial; color: red;}
h1.style2 {font-family: Courier; color: blue;}
h1.style3 {font-family: Arial; color: green;}
You can try to test the way that this new defined style for your document will affect the web page display and to identify the action mechanism of this CSS style by calling the classes name in various situations:
code
This is the default style for h1
This is the first type of style assigned to H1 tag
This is the second type of style assigned to H1 tag
This is the third type of style assigned to H1 tag
In the first place, you will see that if a class name is not included with the h1 tag, the CSS defined in the head of the document does not affect the default h1 style. When you set the class name, it is recommended that you select a name for it that is referring to the class actions instead of an arbitrary name, in order to eliminate confusions and to maintain the desired workflow. You can also define a single class that can be used by many different HTML tags as you see in the last code example.

By using classes you can give your code a modular character, being much easier to be analysed for errors. On the other hand, the code will be smaller, because you can limit the number of style definitions in this way. For testing purposes, here it is the complete HTML code that you can copy and paste in a text document which must be saved as .html type:

code
CSS Classes

h1.style1 {font-family: Arial; color: red;}
h1.style2 {font-family: Courier; color: blue;}
h1.style3 {font-family: Arial; color: green;}
.style4 {font-family: Arial; color: magenta;}

This is the default style for h1
This is the first type of style assigned to H1 tag
This is the second type of style assigned to H1 tag
This is the third type of style assigned to H1 tag
This is a paragraph with style3
This is the fourth type of style assigned to H1 tag