Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Simple Lightbox Preventing the Default Behavior and Using attr()

Werner Chao
PLUS
Werner Chao
Courses Plus Student 1,951 Points

Difference between ID and class

I've been searching around to understand what's the difference between ID and class. Can't seem to find a satisfied answer. My current understanding is class can be used for several elements with pre-written HTML, while ID is for one element only. Can someone explain a bit better? Thanks!

2 Answers

Samuel Key
Samuel Key
3,310 Points

That is basically it. IDs are unique and classes are not. So each element can only have one ID, and only one element should have that ID, while en element can have multiple classes and many elements can share the same class. Also, ID has a higher specificity than class, so if there are conflicting properties, the one with an ID selector will usually win.

CSS Tricks explains it really well: https://css-tricks.com/the-difference-between-id-and-class/

Ha, you got there before me with the link :)

Kevin Korte
Kevin Korte
28,149 Points

Thank you for mentioning specificity. It rarely gets mentioned in a question like this and it's so critical

Hi Werner,

It sounds like you've got the gist of it already. That's the principal thing to remember; IDs can only be applied to one thing on a page, whereas you can have multiple instances of a class on a page.

If you have multiple pages to a site, the ID can appear in each of them, just only one time.

In addition, you can only assign one ID to something. So, this wouldn't be correct, for example:

<div id="menu" id="list">
</div>

But you could add an ID and a class to one element:

<div id="menu" class="main">
</div>

Or even multiple classes (just separate them with a space):

<div id="menu" class="main large mobile">
</div>

I guess the main point is deciding when to use an ID, and when to use a class. IDs are suitable for something that occurs once on a page. Like a main wrapper element, or the top navigation bar. Classes are re-usable, so use them for things that are likely to appear over and over again, like each list item in a list:

<ul>
   <li class="red"></li>
   <li class="red"></li>
   <li class="red"></li>
</ul>

A good reference (if you haven't seen it already): https://css-tricks.com/the-difference-between-id-and-class/.

All the best,

Ede