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

CSS

id vs class

What is the difference between id and class selectors. When do you use one over the other?

5 Answers

IDs are unique and used only once per page. Classes are not unique and can be used on multiple elements.

Mike already explained the main uses perfectly and I just want to add an example:

<ul>
  <li id="item-1" class="items">ITEM 1</li>
  <li id="item-2" class="items">ITEM 2</li>
  <li id="item-3" class="items">ITEM 3</li>
</ul>

Because IDs are unique, I set them for one single li. If I want to target this particular li (eg item 1), I can use #item-1. But if I want to target all items (eg to give it a border) then it is easier to use .items class

I hope that was helpful, Patrick :-)

Nice example!

I highly recommend reading this approach respective of when to use ids vs. classes.

https://github.com/stubbornella/oocss/wiki

Don't forget the different specificity weight that an id and a class holds. This can really create some unexpected results if you're not careful with it.