CSS – ID vs Class

After hacking apart & cleaning up code for the better part of the day, I’ve decided to set the record straight about CSS, IDs, and Classes. The question is “when should I use an ID, and when should I use a class?” Is it that big of a deal?

The big issue is that people who just write Cascading Style Sheets usually won’t run into problems if they are more lax with their use of IDs. Its the people after who coming in trying to add advanced JavaScript features that will end up becoming very, very frustrated.

Why does it matter? Because an ID and Class have one major difference:

ID is supose to be 100% unique to a single HTML element through the entire HTML document. Class can be shared among many elements.

Example:

[html]

This is using an ID

This is using a class

[/html]

What is the big deal? For CSS designers, not a whole lot. In fact, IDs have a higher specificity, so some CSS designers default to using an ID just because it is more convenient. The problem is when your boss say “hey, we need two paragraphs.” The developer copies a new paragraph in and to keep the formatting, adds another ID tag. Now we’ve broke the rule about only having one ID in an HTML document. Sure, it renders fine, but if a JavaScript developer tries to add additional features, they will have to code around these problems.

So when should you use ID and when do you use a class? Here is my rule of thumb:

Unless you are 100% sure that you will never, ever have a duplicate element name on the same page, use a class. When in doubt, use a class. Only use an ID when you’re positive it will always be unique.

Examples of when I would use an ID are:

  • Unique parts of page layout:
  • Identifying specific items:

If it doesn’t fall into those two categories, I usually won’t use an ID. Most of the time, I’ve never had moment where I wished a developer had used a ID instead of a class. But I’ve had many times where I wish an element used classes intead of ID.

2 thoughts on “CSS – ID vs Class

  1. “Unless you are 100% that you will never, ever have a duplicate on the same page, use a class. When in doubt, use a class.”

    That doesnt really make sens 😉

    Like

  2. lol, I fixed a missing word and added an extra sentence to help add clarity.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close