1. Technology
Send to a Friend via Email

Using Style Classes and IDs

Classes and IDs Help Extend Your CSS

By

There are many ways to apply styles across a document, but often you want to use a style on some of the tags in a document, but not all instances of the tag. Or, you may want to create a style that you can apply across several tags in a document, without repeating the style rule. To do this, you use the class and id HTML attributes. These attributes are global attributes that can be applied to nearly every HTML tag.

Class

The class selector allows you to set multiple styles to the same element or tag in a document. For example, you might want to have certain sections of your text called out in a different colors from the rest of the text in the document. You would assign your paragraphs with classes like this:

<style type="text/css">
  p.blue { background-color: #0000ff; }
  p.red { background-color: #ff0000; }
</style>

Then, when you want to call the various classes you would use the class attribute within the paragraph (<p></p>) tag. Any tag that did not have a class attribute would be given the default style for that tag. For example:

<p class="blue">
This paragraph would have a blue background.
</p>
<p>
And this paragraph would default back to the normal style.
</p> <p class="red">
And this paragraph would have a red background color.
</p>

If you want to use a single class across multiple HTML elements, simply remove the HTML element from the beginning of the style call (be sure to leave the period (.) in place):

<style type="text/css">
.blue {background-color: #0000ff;}
.red {background-color: #ff0000;}
</style>

These two classes are then available to any element that needs them:

<p class="blue">
This paragraph would have a blue background.
</p>
<h2 class="blue">And this h2 would also have a blue background.</h2>

ID

The ID selector allows you to give a name to a specific style without associating it with a tag or other HTML element. You write an ID code like this:

<style type="text/css">
#indent1 { text-indent: 10px; }
</style>

You associate an ID tag the same way you associate classes, within the element that should have that style:

<h3 id="indent1">

You can give your ID tags any grouping of letters and numbers that you would like. It's a good idea to give your ID tags names that you will remember and understand a few weeks or months later.

Keep in mind that HTML standards require that the ID must be unique.

Note: One of the trickiest things about CSS is that it requires the use of formerly optional ending tags (as does XML). For example, if you have a style applied to a paragraph tag <p>, the browser may not know where to end that style if you do not include the ending tag </p>.

Most Recent Articles

©2014 About.com. All rights reserved.