ID and Class what's the difference?

Published Wednesday, September 12, 2007 By Steven Stewart

Introduction

It's a common question what is the difference between ID and Class?  I know when I started out I just defaulted to using classes for everything, well in this short article I will describe the differences and offer suggestions when you should use one over the other. 

The code for this article can be downloaded from here.

Differences

An ID can only be used once per page and as the name suggests is a unique identifier to an element.  Typically an ID is used for unique page elements for example the header, content or footer.  Applying an ID is pretty straightforward, add id="name" immediately after the opening tag within an element.  See the example below.

 

<body>
    <div id="header">
        My header
    </div>
    <div id="content">
        My contents
    </div>
    <div id="footer">
        My footer
    </div>
</body>

 

To create a rule for an ID in the style sheet, prefix the ID with a "#".

 

#header {
    border:dotted;
}

 

A Class can be used multiple times per page, making it an extremely powerful and flexible way of applying CSS.  Classes are useful for applying styles and formatting consistently across a page or application.  To apply a class add the class="name" attribute to an element, for example;

 

<p class="highlight">Contents in blue bold writing</p>
<p class="default">this is the contents in black writing</p>
<p class="default">more contents in black writing</p>

To create a rule for a class in a style sheet, prefix the class name with a ".".

 

.highlight {
    color:Blue;
    font-weight:bold;
}

 

When to use an ID

An ID can only be used once per page, therefore ID's should be used only for unique elements such as a header, footer or content. 

Though you can use a class in the same way to identify elements, an ID can make your markup clearer for example if you see an element with the id="header" then you know that this is the header element that usually contains logos etc.  An element with a class="header" might indicate that there are number of such elements on a page.

When to use a Class

Classes are a flexible method for applying CSS rules and can be used multiple times within a page.  Use classes to control elements that belong to group, for temporary items and to enhance the behavior of an ID.

Conclusion

In conclusion, I recommend that you use ID's for the main structural elements of your page and classes for styling and formatting that will be applied multiple times in a page.