What is the difference between a class and an id?

Each of these terms allow you to create CSS properties that are personalised, that you can apply to tags.

Fundamental difference:

You can use id or class one for the other, but...

For example, it is possible to have the code below:

<div class="test"></div>
<div class="test"></div>

But you can't have the following:

<div id="test"></div>
<div id="test"></div>

The id must designate only one object in the document. You can define as many id you want within your CSS style sheet, but each need to identificate one element only.

For stricter code, you must priviledge correct syntax. Use id first when you can, and class when you can't use id.

For example: start using id by default for unique objects to make it easier to read the code. For example, give your body tag an id, then to your header block, your left block, your right block, ... but for all paragraphs or menu lists, use classes since there are several elements of this type.

Advantages and inconvenients:

What is the use of an id that can be used only once when you can use classes instead?

There are several reasons for this, here are the main ones:

Note: by reading a few Alsacreations tutorials, you will certainly notice a few incoherences concerning this article, especially concerning the use of class when id would have been more appropriate. Some of the tutorials were written a long time ago and have not been revisited yet!

Print article

Raphael GOETTER
www.alsacreations.com