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>To use your class, all you need to do is add the 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>I am red, so I'm important.</DIV>Now you will get the text in a red font:
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>I am red, so I'm important.</DIV>
<DIV>I am green, so there.</DIV> And now you have what you wanted:
I am green, so there.
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 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.
Using an external style sheet
Well, suppose you would like to be able to use one group of styles- but you want to use them on many pages at once. This can be done through the use of external style sheets.
To begin, open your style.css and enter the following information:
DIV { font-family:Arial }
.redfont { color:red }
Now, save the file.
Now, any time you use the DIV tag in one of your pages linking to the style sheet, you will get an Arial font:
<DIV>I am Arial!</DIV>