Unrestricted Access

Web Standards

Class or Id?


A lot of people come with the question "When do I use Class and when do I use IDs... what is the difference?". This article talks about the differences and IDs can be used with other applications other than CSS.

The Difference

Both classes and ids can be referenced with CSS using . and # respectively. However, ids can only be used once per page, whereas classes can be used as many times as required.

"So why not always use classes" - well because ids are unique to that page they can be addressed in scripts, forms and CSS without the possibility of them being found anywhere else on the page.

Ids also have precedence over classes so classes can not be used to override id styled elements.

Application of IDs


The best example of the use of ids uniquely used on a page, is within forms. An id on a input element is used to connect it to the label element.

<label for="id_name">
<input type="text" name="parse_variable" id="id_name">

Because ids can only be used once per page, it is obvious that the label belongs only to the one input element.

Internal Linking

Ids make sense for elements that will only appear once on a page, such as navigation, footer and content containers. Because of this identification they can be referenced with interal links using the id name.

<a href="www.domain.com/page.html#footer">Go to the footer</a>

<div id="footer"></div>

Finally, ids are an important part of the DOM, for accessing HTML elements and in client side scripting techniques such as Javascript.

Further Reading & Resources

Below are resources I used for this article and would be interesting further reading on the subject.

CSS Classes vs ID

There is often confusion when it is appropriate to use CSS IDs and when CSS Classes should be used instead. This lesson is geared to display an answer as well as provide more information about CSS IDs


Class and ID Selectors

The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one.