<?php the_title(); ?>

What’s the difference between an id and a class selector in CSS?

IDs and classes are both used in CSS to select (hence the name “selector”) items you would like to add styles to. However, that’s about where the similarities end.

So how are IDs and classes different?

IDs are unique to a document, classes aren’t
Most people know this by heart because someone already drilled it into them. IDs are unique to a document, while classes don’t have to be. What’s this mean?

So lets pretend for a second we’re not talking about page elements at all, lets say, we’re talking about people in a classroom. So if I say, “Sarah Yates, please come to the front of the room.” I’ll only get one person this is like what happens when you use an ID to select an item. Conversely, lets say I asked, “Can all the females come to front of the room?” I’ll get all people who fit that description, this is like using a class selector.

So, in context, you can only have one id in a document with the value of “header”, and you can have multiple classes in a document with the value of “widget”.

Two is Better Than One?
You can declare multiple classes in one tag class attribute, you can’t declare multiple ids. So for instance:

<div id=”header” class=”class1 class2″></div>

Just remember to declare the multiple classes with a space in between them. Otherwise, neither class will show up.

Developers Love Their IDs
IDs are used in a variety of back-end languages, so be careful when naming or using IDs that you’re not stepping on your developer’s toes. If you’re working with a back-end developer make sure to talk to them about how they use IDs in their code and come to a consensus as to how you’re going to effectively share ID attributes.

But, when do you use which one?

Is this styling appearing on a page only once EVER?
When planning out CSS style selectors, I go with this one major rule.  If the answer is yes, using an ID is appropriate, but if you’re planning on using the styling more than once, say for instance, you plan on having more than one “widget” per page, then use a class.

4 responses so far

  • Melissa Balkon
    Dec 8, 2009 at 3:15 pm

    Look at you using my question! ;)

  • Rob
    Apr 20, 2010 at 2:28 am

    Thanks for the article

    Do you know what happens if you do use multiple IDs? is it just bad form or would the page fall apart?



  • Perri Collins
    May 2, 2010 at 9:16 am

    I like the analogy.

  • Design Made Better
    Jun 8, 2010 at 8:59 am


    Many browsers do not enforce this rule but it is a basic rule of HTML/XHTML and should be observed. Simply put, it’s bad form. One of two things will happen depending on the browser you’re testing in: 1. the second element using the id will not uphold the styling characteristics or 2. both elements will have the styling.

Leave a Comment