Class or Id?
30.06.2005
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
Forms
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">Label Title</label>
<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="http://example.com/page.html#footer">To the footer</a>
<div id="footer"></div>
Scripting
Finally, ids are an important part of the DOM, for accessing HTML elements and in client side scripting techniques such as Javascript.
1 Bojan 3 days, 18 hours later.
A useful article. I believe it’ll come in handy to many newbies, as well as designers with a bit more experience.
2 Aust 2 months, 1 week later.
Surely the label example should be:
Label text
Putting the field inside the label makes the need for a label redundant.
A label should be used to identify the field, i.e. Name when the label is clicked, it will section the field which it’s connected (for=”id_name”).
3 trovster 2 months, 1 week later.
@Aust - Yes, I know now that label elements should be set explicitly, outside of their associated inputs. This is a recommendation in the Web Content Accessibility Guidelines 2.0. I’ll change the example.