Grow your CSS skills. Land your dream job.

The Difference Between ID and Class

Published by Chris Coyier

ID's and Classes are "hooks"

We need ways to describe content in an HTML/XHTML document. The basic elements like <h1>, <p>, and <ul> will often do the job, but our basic set of tags doesn't cover every possible type of page element or layout choice. For this we need ID's and Classes. For example <ul id="nav">, this will give us the chance to target this unordered list specifically, so that we may manipulate it uniquely to other unordered lists on our page. Or we might have a section on our page that has no relevant tag to signify it, for example a footer, where we might do something like this: <div id="footer">. Or perhaps we have boxes in our sidebar for keeping content over there separated in some way: <div class="sidebar-box">.

These ID's and Classes the "hooks" we need to build into markup to get our hands on them. CSS obviously needs these so that we may build selectors and do our styling, but other web languages like Javascript depend on them too. But what is the difference between them?

ID's are unique

  • Each element can have only one ID
  • Each page can have only one element with that ID

When I was first learning this stuff, I heard over and over that you should only use ID's once, but you can use classes over and over. It basically went in one ear and out the other because it sounded more like a good "rule of thumb" to me rather than something extremely important. If you are purely an HTML/CSS person, this attitude can persist because to you, they really don't seem to do anything different.

Here is one: your code will not pass validation if you use the same ID on more than one element. Validation should be important to all of us, so that alone is a big one. We'll go over more reasons for uniqueness as we go on.

Classes are NOT unique

  • You can use the same class on multiple elements.
  • You can use multiple classes on the same element.

Any styling information that needs to be applied to multiple objects on a page should be done with a class. Take for example a page with multiple "widgets":

<div class="widget"></div>
<div class="widget"></div>
<div class="widget"></div>

You can now use the class name "widget" as your hook to apply the same set of styling to each one of these. But what if you need one of them to be bigger than the other, but still share all the other attributes? Classes has you covered there, as you can apply more than one class:

<div class="widget"></div>
<div class="widget big"></div>
<div class="widget"></div>

No need to make a brand new class name here, just apply a new class right in the class attribute. These classes are space delimited and most browsers support any number of them (actually, it's more like thousands, but way more than you'll ever need).

There are no browser defaults for any ID or Class

Adding a class name or ID to an element does nothing to that element by default.

This is something that snagged me as a beginner. You are working on one site and figure out that applying a particular class name fixes a problem you are having. Then you jump over to another site with the same problem and try to fix it with that same class name thinking the class name itself has some magical property to it only to find out it didn't work.

Classes and ID's don't have any styling information to them all by themselves. They require CSS to target them and apply styling.

Barcodes and Serial Numbers

Maybe a good analogy here is bar codes and serial numbers. Take an iPod in a store. On the packaging will be a bar code. This tells the store what the product is, so when it is scanned, the system knows exactly what the product is and what it costs. It might even be able to know what color it is or where it was kept in the store. All iPod of this same type have the exact same bar code on them.

The iPod will also have a serial number on it which is absolutely unique to any other iPod (or any other device) in the world. The serial number doesn't know the price. It could, but for the store this wouldn't be a very efficient way to store and use that data. Much easier to use the barcode, so that for example, if the price changed, you could just change the price for that bar code and not every individual serial number in your system.

This is much like ID's and Classes. Information that is reusable should be kept in a class and information that is totally unique should be kept in an ID.

ID's have special browser functionality

Classes have no special abilities in the browser, but ID's do have one very important trick up their sleeve. This is the "hash value" in the URL. If you have a URL like http://yourdomain.com#comments, the browser will attempt to locate the element with an ID of "comments" and will automatically scroll the page to show that element. It is important to note here that the browser will scroll whatever element it needs to in order to show that element, so if you did something special like a scrollable DIV area within your regular body, that div will be scrolled too.

This is an important reason right here why having ID's be absolutely unique is important. So your browser knows where to scroll!

Elements can have BOTH

There is nothing stopping you from having both an ID and a Class on a single element. In fact, it is often a very good idea. Take for example the default markup for a WordPress comment list item:

<li id="comment-27299" class="item">

It has a class applied to it that you may want for styling all comments on the page, but it also has a unique ID value (dynamically generated by WordPress, nicely enough). This ID value is useful for direct linking. Now I can link directly to a particular comment on a particular page easily.

CSS doesn't care

Regarding CSS, there is nothing you can do with an ID that you can't do with a Class and vise versa. I remember when I was first learning CSS and I was having a problem, sometimes I would try and troubleshoot by switching around these values. Nope. CSS doesn't care.

Javascript cares

JavaScript people are already probably more in tune with the differences between classes and ID's. JavaScript depends on there being only one page element with any particular, or else the commonly used getElementById function wouldn't be dependable. For those familiar with jQuery, you know how easy it is to add and remove classes to page elements. It is a native and built in function of jQuery. Notice how no such function exists for ID's. It is not the responsibility of JavaScript to manipulate these values, it would cause more problems than it would be worth.

If you don't need them, don't use them

As you can see, classes and ID's are very important and we rely on them every day to do the styling and page manipulation that we need to do. However, you should use them judiciously and semantically.

This means avoiding things like this:

<a href="http://css-tricks.com" class="link">CSS-Tricks.com</a>

We already know this element is a link, it's an anchor element! No particular need here to apply a class, as we can already apply styling via its tag.

Also avoid this:

<div id="right-col">

ID is appropriately used here as the page will likely only have a single right column, but the name is inappropriate. Try and describe the context of the element, not where it is or what it looks like. An ID here of "sidebar" would be more appropriate.

Microformats are just specific class names

Think microformats are over your head? They aren't! They are just regular markup that make use of standardized class names for the information they contain. Check out a standard vCard:

<div class="vcard">
  <a class="fn org url" href="http://www.commerce.net/">CommerceNet</a>
  <div class="adr">
    <span class="type">Work</span>:
    <div class="street-address">169 University Avenue</div>
    <span class="locality">Palo Alto</span>,  
    <abbr class="region" title="California">CA</abbr>  
    <span class="postal-code">94301</span>
    <div class="country-name">USA</div>
  </div>
  <div class="tel">
   <span class="type">Work</span> +1-650-289-4040
  </div>
  <div class="tel">
    <span class="type">Fax</span> +1-650-289-4041
  </div>
  <div>Email: 
   <span class="email">info@commerce.net</span>
  </div>
</div>

Comments

  1. Nice article!

  2. Wow, I had no idea about anchor linking IDs. You learn something new every day, I guess : ]
    Thanks.

  3. Jeff Dion

    Nice post. Nothing new for me, but i like the way you explained everything and made it simple :D

  4. This was hard for me to understand when i was first learning about css. The barcodes vs serial numbers example helps alot! Thanks!

  5. GetElementById = getElementById.. and its not Javascript its DOM ;p
    nice article :P

  6. ha! i also just noticed that your # of rss reader messages changes on page refresh! thats cool – howd you do that?

  7. Great article.

    I had a vague understanding about microformats but didn’t know they were just specific class names – thanks!

  8. Ivan Nikolic

    Nice article, Chris!

  9. Great post. Perfect primer and refresher. Thanks.

  10. Nice article. Even for us experienced developers, some of these basic reminders can be refreshing. And it also comforts me to know that I can blog about simple stuff once in a while.

    Just a small point on the use of ID and CLASS within the same tag: I find this a very useful technique when you want to have default styles applied to an element in all circumstances (via the ID) but change its color or background image dynamically (via the class value) on different pages. However, I’ve found this method seems to cause problems in IE6, so I tend to shy away from it. Anyone else had this problem? I’m sure it’s documented in Sitepoint’s CSS reference, but just thought I’d mention it.

  11. Great article. I remember when I first started out, I used id for everything because I was obsessed with doing everything with the fewest amount of characters possible.

  12. Excelent article! I think the way you explained the thing will help beginers to understand this diference between id’s and classes.

  13. Practical article. Thanks, Chris!

  14. Great article as usual, Chris!

    About microformats: I wish there was a way to share email information without opening yourself up to spammers. Microformats are great for sharing other personal/business information, but leaving your email out in the open like that is just begging for an endless onslaught of V1agra offers. One workaround that I have used — not sure how effective it is — is to use the URL of my site’s contact form. Not as direct as an email, but perhaps better than nothing at all..

  15. CSS does actually care in that IDs have much higher specificity than classes. This obviously needs thinking about in terms of which CSS rules will override each other in any given set of style sheets. I know this isn’t what you where implying in the CSS section but worth mentioning anyway.

  16. That’s a great analogy with barcodes and serial numbers. Ed Eliot (comment 15) bring a good point.

  17. nixgrafix

    Thanks a lot Chris, another subject well explained and easy to understand !
    Please keep these ‘basics’ coming they are sooooo useful for us beginners.

    Nic

  18. Biofobico

    Great article Chris.

    And now time for the big noob question;

    What’s a vcard?

  19. You should do a poll on how long it took people to figure out that you can have multiple classes… It too me a good number of years. No sites that I went to ever brought it up and I never really noticed it when viewing other website’s code. Maybe it was just how I taught myself HTML and CSS.

  20. Alan C

    I’d like to second Ed’s point (in post 15, above) that CSS does in fact care about the difference between IDs and classes, because an ID always has a higher specificity than a class.

    This means that if you have separate ID and class-based style declarations that both declare the same property for the same html element, the value from the ID selector is the one that is going to be applied.

    Specificity conflicts are probably one of the biggest traps for young CSS players, so it is worth being careful about one’s language in this area

  21. once again an awesome posting here.. thanks so much for providing this great resource to all of us for nothing. your awesome. i cant wait for the next posting on the wordpress series as i am in the process of redoing my portfolio website and powering it by wordpress

    thanks

    Tom

  22. Permalink to comment#

    “An ID here of “sidebar” would be more appropriate.”

    Nope, “secondaryContent” would be more appropriate since sidebar is still a presentational description. In the context of the HTML it is not a sidebar, it most likely comes after the mainContent. Of course it may be in a different position within the HTML and not secondary, but the idea is to keep ID’s and classes descriptive to the context.

  23. It was fun reading about the bar codes and serial numbers =)

    Personally I prefer using classes for my CSS, leaving ID’s for JavaScript.

    Thanks for a fun article.

  24. Thanks so much for the article. I, being a css beginner, found it very useful!

  25. It’s funny…when I was first starting out with CSS, I was confused as to what the differences were between IDs and classes too. I actually couldn’t find any information on it, because it’s considered such a basic thing that nobody actually explains it anywhere! I could find plenty of tutorials and example code, but they would always just use an ID or a class and never explain WHY it was being used. So it actually took me a pretty long time to figure it out on my own.

    The key thing that I kept getting confused with is this – there ARE no stylistic differences between an ID and a class. The only differences are in how they’re used, not how the browser displays them. As soon as I realized that, everything else got much easier.

    I really wish somebody out there had written an article like this years ago! Would have saved me a lot of frustration :-P

  26. Great article, thanks for helpful information.

  27. Great Article i was sketchy about this for a long time, thank you for posting this! Since someone scrolled down here, lets take advantage of those IDs shall we!

    http://css-tricks.com/the-difference-between-id-and-class#blog

  28. Love your anecdotes of what you thought when you were learning. Like the class name being magic… good way to put noobs at ease!

    I’m with Dan, it took me a couple of years to figure out that you could add two classes to an element. It’s such a useful feature! I think I only learned recently that only one element on the page should have a certain ID. I guess pages still render if you have multiple ones though? Maybe by some stroke of luck I managed to never repeat ID elements.

    Also had never heard of naming elements to describe their content. I just thought you named it so that it made sense to you.

    I’ve never heard of CSS taking the ID with more weight or specificity than the class as people have said in the comments. I didn’t really understand what they meant, so I did a quick test. If a div with an ID and color specified also has a class with color specified, the class color has no effect on the text inside the div.
    Thanks for mentioning that guys! Pretty useful info because I always thought the CSS hierarchy was purely order based.

  29. Gordon
    Permalink to comment#

    One thing you forgot to mention, an element can only have one ID but it can have several classes. is perfectly valid, and it will inherit the CSS rules for all 3 named classes (except in IE6, but then again, what works properly in IE6 anyway?)

  30. Gordon, see the sections titled IDs are unique and Classes are not unique, I’m doubt those facts could be any clearer. ;)

  31. jean
    Permalink to comment#

    Thanks for a very interesting and well documented article.
    I know trying to improve my CSS and HTML knowledge level is not easy but you are succedding !!
    Keep up the good work and thank you !
    Jean from France

  32. Chris,

    You are the best. Thanks for the article I learnt heaps. Also, I too used to swap classes for ID’s for a while there thinking that it would make a difference.

  33. Mike
    Permalink to comment#

    Actually CSS does care if you use an id or a class. In the Cascade of a style sheet an id has more weight that a class. Meaning if both a class and an id are trying to change the same property one on one id will (should) always win

    given this css

    #mysample{
    color : red;
    }
    .mysample2{
    color: black;
    font-weight:bold;
    }

    If both the class and id are applied to the same element the color will be red. Only the font-weight of the class selector is applied from to class since it wasn’t specified by the id.

  34. Mark
    Permalink to comment#

    Quick question What is the difference in these statements.

    #colright {
     . . .
    }
    div#colright {
     . . .
    }
  35. @Mark: Not much, just one extra “point” of specificity for the one that starts with div. Sometimes it helps you keep organized as well.

  36. It isn’t merely an extra point. The difference is that the first one can be applied anywhere in the HTML code. The other one can only be applied to div elements.

  37. Permalink to comment#

    That’s right:

    This means that if you have separate
    ID and class-based style declarations
    that both declare the same property
    for the same html element, the value
    from the ID selector is the one that
    is going to be applied.

    ID’s are above the CLASSES

  38. Mark
    Permalink to comment#

    Thanks

  39. Rana A. Ahad
    Permalink to comment#

    Great info dude… Thnx !! I am newbie and I had few confusion with css which is now over…. your post really helped me out with…

  40. Great article. Thanks, Chris!

  41. Ramanan Kalirajan
    Permalink to comment#

    I am begining my corporate experience as a UI designer i was doing the code as the way it flows. But after reading ur post it really made me to understand the exact difference between the class and ID’s. The url with #id is really new for me. Hope i can use it. Thanks a lot.

    Regards
    Ramanan Kalirajan

  42. Permalink to comment#

    Thanks!!! I needed this :D

  43. Permalink to comment#

    Very well written and explained. Thank you – clears out quite a bit of foggyness that surrounded these things :)

    -gowtham

  44. Vishvendra Singh
    Permalink to comment#

    Thanks!! Your post helped alot in clearing my doubts about the diffenced regarding id and class.

  45. Nomad
    Permalink to comment#

    I’ve been designing pages for years where I use the same div/ID over and over on the same page. And never had a problem that I’m aware of. I never have linked to a div, and other than that it obviously does work OK to use the same ID multiple times. I will however change this practice. I thought you had to use ID with a div and had to use class with a span. that’s how it was explained in the one an only “HOW to” book I read years ago. It looks like it’s more like this: You have to use an ID with a div but can use class with either div or span. In fact I found this page because a did a search… suspecting I needed to know more about the difference.

  46. Abdoo
    Permalink to comment#

    I really like the part about scrolling the page with # in the address. Very interesting. Thanks

  47. Rafi
    Permalink to comment#

    **the class tag how identify in css file

  48. 2 years ago, i got this question in a technical job test and i could nt answer it perfectly :)

  49. Jim
    Permalink to comment#

    Thank you. It’s so encouraging to see that others have struggled with CSS. I almost gave up because I thought I was too slow. Now I want to keep learning.

  50. Craig
    Permalink to comment#

    Get rid of the apostrophes. The correct spelling is IDs. The apostrophe implies it possesses something and is not used for mere plurals under any circumstances.

  51. Federico
    Permalink to comment#

    Actually CSS cares. ID css properties will override CLASS properties by default, ignoring the css flow. This just confirms your point, of course: just use classes for styling, or your css will be a mess of !important declarations.

  52. Norden
    Permalink to comment#

    Very nicely explained !

  53. Kalif Gates

    Thank you for explaining this. I am currently taking a class on web design and in the example, the instructor used id instead of class but on my website I had already used the class attribute to define my divs. It is good to know that there isn’t much of a difference between the two so I do not have to go back and change all my classes to ids. That would be a lot of code to change. Again, thank you for the explanation. It is greatly appreciated.

  54. sukh

    good eg., bt 1 thing is that id is unique mean that id will always with those elements where we have to use only one element in a div.like

    and class containing multiple div’s ….like classes in java.

  55. mrochlin

    I’m using the Foundation 5 framework and I’ve found sometimes Foundation will ignore custom formatting I put in a class (with my own class name – not overlapping w. Foundation names) but for some reason obeys if I put in an ID. I have multiple buttons with the same ID, and it seems to work to make button text bolder on phones. Though I guess having multiple elements with the same id is not kosher and I may be in for some ass biting in the future.

    Anyway, IDs seem like one work around for customizing a framework that’s adamant about it’s own style choices.

  56. James

    Excellent explanations and analogies. Thank you for that.

  57. Abhimanyu

    So why we use id’s… i mean we can give a particular element properties like font-style etc. etc. in the html only…. so why to use CSS??? Do CSS have any advantage in id’s?

  58. Chris, This is an excellent post. Thank You.

    Your code formatting looks elegant, do you use some wp plugin or is it custom coded?

  59. your mom
    Permalink to comment#

    CSS does care! (ids have priority over classes.)

  60. David
    Permalink to comment#

    Went right over my head. Not getting it at all.

  61. Matt P
    Permalink to comment#

    FYI

    In the third paragraph of the Barcodes and Serial Numbers section, reusable is spelled wrong.

    Also, in the second paragraph of Classes are NOT unique, you have other typed twice in a row.

    But good article nonetheless!

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".