Lesson-4 (Using classes to Declare styles)
Now that you know how to use styles in the head section, you may like to use a method besides defining a tag to have the same style each time you use it. What if you want to have a section of text with a red font and another with a green font, but do not want to use up all the tags you have for a section of text? Well, using a class allows you to change the style of something without the need to use up a tag each time you wish to have a new style.
To define a class, go to the head section of your document, and then go inside the <STYLE> and </STYLE> tags. A style definition would look like this:
<HEAD>
<STYLE type="text/css">
<!--
.redfont { color:red }
-->
</STYLE>
</HEAD>
The name of our class is "redfont". Notice the dot that comes right before the name of the class. This notifies the browser that this is a class definition and not a tag definition. After that, we define the style the same way we did before.
So, if you want to declare one class that gives you a red font, and another that gives you a green font, you would type the following:
<HEAD>
<STYLE type="text/css">
<!--
.redfont { color:red }
.greenfont { color:green }
-->
</STYLE>
</HEAD>
Okay, now that we have our classes set up, we need to see how to use them later on in the body section of the page. To use your class, all you need to do is add the class=" " attribute to the tag you wish to have the style of your class. So, if you wanted a line of text to be red, you could add the class attribute to a <DIV> tag, like this:
<DIV class="redfont">I am red, so I'm important.</DIV>
Now you will get the text in a red font:
I am red, so I'm important.
Now, if you would like to have a section with a red font and a section with a green font, but wish to use the DIV tag for both, you can!
<DIV
class="redfont">I am red, so I'm important.</DIV>
<DIV class="greenfont">I am green, so there.</DIV>
And now you have what you wanted:
I am red, so I'm important.
I am green, so there.
Now that you know about classes, you may want to see an ID. These are used in the same way, but rather than using a dot before the name, you use a number sign (#).
<HEAD>
<STYLE type="text/css">
<!--
#redfont { color:red }
#greenfont { color:green }
-->
</STYLE>
</HEAD>
And when you wish to use the ID later, use the ID=" " attribute:
<DIV
ID="redfont">I am red, so I'm important.</DIV>
<DIV ID="greenfont">I am green, so there.</DIV>
And you get the same thing we got with the class definition:
I am red, so I'm important.
I am green, so there.
Using classes and ids, you can begin to see what style sheets can do for you. If you had a bunch of text sections in green and wanted them all to be light green instead, you would only need to change the style definition of the class "greenfont" in your head section, rather than changing 5 or 6 <FONT> tags.
If you would like this effect to work accross multiple pages, then you will want to use an external style sheet.