CodeinWP CodeinWP

What’s the Difference Between Classes and IDs in CSS?

When applying CSS styles to an element in your HTML, you’ll be using different CSS selectors to target your elements.

Two of the most common selectors used in CSS are the “class” selector and the “ID” selector. There are many others, but this post will focus on these two, and I’ll describe the difference so you’ll know the potential effects of using either of these selectors.

The ID Selector is Very Specific

An ID is defined in your HTML like this:

<div id="element">
<!-- stuff goes here... -->
</div>

And in your CSS you can target the element, and apply styles to it, like this:

#element {
    background: blue;
}

CSS styles are applied based on rules relating to the cascade and specificity. Because this is a post aimed at CSS beginners, I’m not going to go into the gory details of those subjects. If you want to delve into this, there’s a nice article on Smashing Magazine by Inayaili de Leon that might be worth a peek.

The specificity of a selector can have a profound effect on the future maintenance and debugging of your CSS code. So, with that in mind, do realize that if you choose to use the ID selector, you may end up causing specificity issues that will force you later in development to use even stronger selectors. This could easily get out of hand and cause your stylesheet to be less maintainable and bloated.

Styles in a CSS file are supposed to “cascade”. So, theoretically, this should allow styles declared later in your stylesheet to override styles that are declared earlier. But because of more specific selectors (like IDs), this doesn’t happen as often as we’d like.

For example, if you had the following HTML:

<div id="element" class="element">
<!-- stuff goes here... -->
</div>

And CSS:

#element {
    background: blue;
}

body div.element {
    background: green;
}

Even though the body div.element selector appears after the #element ID selector, and despite the fact that the “body” element is included as part of the selector, the background of the element will be blue — not green — because the ID selector is more specific than the second selector, and the natural cascade has been overridden.

It may seem at first glance to be an advantage to have a very specific selector. But in the long run, this is not a good thing. Also, because an ID has to be unique and must only appear once per HTML page, you can’t reuse the styles on an ID selector, so your stylesheet will be much larger if you end up using a lot of IDs.

Class Selectors are Much Easier to Work With

Classes are applied in HTML like this:

<div class="element">
<!-- stuff goes here... -->
</div>

And you target the element in your CSS like this (which, I’ve already demonstrated in the previous section, really):

.element {
    background: blue;
}

Class selectors are, in my opinion, highly underrated and a much cleaner and easier to use option for applying styles to elements. There are a number of reasons for this.

Classes can be reused (you’re not limited to a single class per page, like IDs). This allows you to avoid repeating styles unnecessarily. You can also include multiple classes using a single attribute, like this:

<div class="element class2 class3">
<!-- stuff goes here... -->
</div>

You also have the option to chain your classes using selectors like .element.class2.class3 (notice no spaces between the classes). While this is possible, you should know that this method is buggy in IE6, which is why these types of chained class selectors have been largely avoided for so many years.

And best of all, class selectors are not extremely specific. So a class of .element will override the less specific element selector (e.g. a plain span or div selector), but it will not override other classes — unless it appears after those classes in the CSS.

This is great for maintenance and debugging of your CSS, because when you add new classes to your CSS, you won’t be scratching your head wondering why the styles don’t take effect right away.

Final Notes

So my advice is: Don’t use IDs as CSS selectors unless you have really good, practical reasons for doing so. Use classes abundantly and allow the natural cascade to work its magic.

This doesn’t mean you won’t use IDs. You will still need IDs for in-page links (i.e. fragment identifiers), and for JavaScript and jQuery hooks.

You might think: What if there’s an element on the page that already has an ID (for non-CSS reasons), and it’s an element that you absolutely know is going to be unique and won’t have repeated or reusable styles? Well, in my opinion, even in this case, there is no reason to use the ID selector in your CSS, and you should still use a class instead.

If you take each one as a stand-alone selector, regardless of all other styles and selectors, there is no difference between #element and .element. But when you factor in the negative effects of an ID selector (the non-reusability, the high specificity, the detriment to the cascade), I think the class selector is much more powerful and should be an overwhelming choice.

Finally, if you want to get into some more good reasons to use classes heavily, you can check out my recent Smashing Magazine article covering Object Oriented CSS.

22 Responses

  1. Paul says:

    I agree with you using classes in CSS I always use classes first and if I have to I will use ID’s, but tend to just use IDs for jQuery selectors for speed reasons.

  2. l2aelba says:

    HTML :

    <div class="element" id="one">
      <!-- stuff goes here... --> 
      </div>
    <div class="element" id="two">
      <!-- stuff goes here... -->
    </div>
    

    CSS :

     
    .element { background : #000; display:none;} 

    jQuery :

     
    $('.someOne').hover(function () {
    $('#one').show();
    });
    
    $('.someTwo').hover(function () {
    $('#two').show();
    });

    I use only like this :P

  3. 5741326792 says:

    This is an amazing article. You may post more articles of this class.

  4. Michael Gunner says:

    You should probably mention in your article that IDs have a Hash Value and classes do not.

  5. Bharat KV says:

    Very true… Classes are much more effective and serves its purpose when it comes to Styling. ID are more of identifiers. Using them to style elements is not a wise idea… Very well explained.

  6. Megan Dean says:

    You make very good points for choosing the class attribute over the id attribute. Planning for the future is important in web design. I will be using ‘class’ from now on.

    While I am not a total newbie, I have found something from each of your “CSS Beginner” posts to add to my notes. So, thanks for starting this column.

  7. Aakash says:

    i use ID many times.I think i should start using classes.Thanks!

  8. you can’t reuse the styles on an ID selector, so your stylesheet will be much larger if you end up using a lot of IDs.

    That’s not true. Say you have 4 elements with the IDs “foo”, “bar”, “baz” and “quz” you want to style the same, you need to write the declarations only once:

    #foo, #bar, #baz, #quz
    {
      /* various styling */
    }

    Classes can be reused […] This allows you to avoid repeating styles unnecessarily. You can also include multiple classes […]

    You are suggesting to write the stylesheet first, the markup later? That’s a highly questioinable workflow.
    It’s better to write the markup first – without any thinking about visual presentation. That comes later. Keep markup and presentation apart, cf. Meiert. Don’t use presentional class names.

    So my advice is: Don’t use IDs as CSS selectors unless you have really good, practical reasons for doing so.

    My advice is: Use IDs as CSS selectors because you have no really good, practical reasons for not doing so.

    check out my recent Smashing Magazine article covering Object Oriented CSS

    If you do, be sure to check out the (negative) comments on that article as well. There are pretty good reasons against OOCSS.

    • Lewis Le says:

      I think your (negative) comment is a little aggressive.

      Use classes for styling elements and IDs for javascript. That’s my point.

      Because doing so will help devs easier to figure it out and build more consistent code. Instead of thinking about whether to use ID or class, why don’t you just follow the above convention (classes are for styling), it’ll save your time. For more than 3 years dealing with CSS, I myself found that there is no reason to use IDs for styling stuff, while classes are reusable.

      Thank Louis for all of your posts! :)

    • Ryan says:

      While you are correct with respect to the physical size of the file, when the browser needs to read the file, you are incorrect. Say you have the code you referenced:

      #foo, #bar, #baz, #quz {
      /* various styling */
      }

      When the browser reads the code, it reads it like so:

      #foo {
      /* various styling */
      }

      #bar {
      /* various styling */
      }

      #baz {
      /* various styling */
      }

      #quz {
      /* various styling */
      }

      But say you define it like so:

      .foo {
      /* various styling */
      }

      Then the browser only has one rule of code to read, rather than 4. Sure, it will still need to render just as many properties altogether. But the process for reading in the code will be a little slower.

    • Ryan says:

      …will be a little slower with your technique.

  9. The difference between classes and IDs has nothing to do with CSS.

    With classes, you classify elements; with IDs, you identify elements. Simply as that.

    Example: Let our elements be a bunch of people. Classes might be “female”, “male”, “web developer”, “Bruce Springsteen fan”, … Of course, a person may belong to multiple classes.

    Each person may have an ID, eg. the passport number. Needless to say that IDs must be unique.

    Now I leave it up to you to translate this concept to HTML elements. Yet the difference between classes and IDs still has nothing to do with CSS.

  10. konou says:

    Gunnar Bittersmann, clears things out in his preceding comments.

    IDs and Classes are used to define the semantics of the element. Their purpose is not for being used exclusively in css.

    It would be extremely helpful to run some benchmarks on different browsers and see which selector is faster. This is something that css coders would need to know.

    • It’s not correct to say “IDs and Classes are used to define the semantics of the element.” IDs and classes have nothing to do with semantics. They are selectors to help you target elements. Targeting with an ID is exactly the same as targeting with a class. There is no difference between the two, except for specificity. And because specificity is a bad thing, it’s always best to use a class instead.

      Think of an ID selector the same way you view a JavaScript bad practice (like eval or global variables). You avoid it and use a different method instead.

  11. i use classes only for css styles and when i need to group elements somehow. and ids for addressing to a certain element in js

  12. hoga says:

    but why if id’s are unique and you create styles for id and use again the brow render without error? for example i know that this code is absolutely wrong but it works! why?
    <div id=”example”> </div>
    <div id=”example”> </div>
    <div id=”example”> </div>

    you have to use classes like this

    <div class=”example”> </div>
    <div class=”example”> </div>
    <div class=”example”> </div>

    • Because HTML doesn’t produce errors, so it makes up for the mistake on its own. You’re probably right, the IDs example shouldn’t work, but it still does. I’m not sure if every browser is the same, though.

  13. subhi says:

    Is this correct

  14. martin says:

    “because the ID selector is more specific than the second selector,”

    Can you explain this a bit more? Why is it more specific?

    • Every CSS selector has a level of ‘specificity’ that’s built in. ID selectors (e.g. #example) have a very high specificity, so in that example, you can’t override it unless you use something more specific than ID, and there isn’t really anything more specific than ID other than combining ID with another selector.

  15. haseeb says:

    Please read the below short article and know the difference between class and id attributes.

    http://www.thesstech.com/html/attributes

  16. Carl says:

    Thanks for the great article – it lists out the selector concepts clearly and makes the points easy to comprehend!

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).