July 21, 2010

IDs vs. Classes?

IDs should generally be used when the element is unique, whereas classes should be used when there are a lot of similar elements that need the same styling. It would be perfectly legal to use IDs for every single element on a page (if they are unique, of course), but this would be terribly bad style for two reasons.

One, your ID names will start to get pretty long and complicated.

Two, if there are certain elements that share the same styling, you'll have to duplicate code! Why not just label them as the same class, type out a class styling once and apply it to both of them?

For example, you could have many articles labeled with separate, unique IDs.

<div id='article1'></div>
<div id='article2'></div>
<div id='article3'></div>

If you want to apply some styling, your CSS would look unnecessarily long and not DRY (don't repeat yourself) at all!

#article1{
color: blue;
padding: 2em;
}
#article2{
color: blue;
padding: 2em;
}
#article3{
color: blue;
padding: 2em;
}

What if you just had some class article, and applied a class styling to all of the articles?

<div class='article'></div>
<div class='article'></div>
<div class='article'></div>

.article{
color: blue;
padding: 2em;
}

There, that's better. And of course, if you need each article to have a specific ID for some javascript effect purposes, you can include both a class and an ID:

<div id='article1' class='article'></div>
<div id='article2' class='article'></div>
<div id='article3' class='article'></div>