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 CSS Basics (2014) Basic Selectors ID and Class Selectors

Zach Robinson
Zach Robinson
8,862 Points

Why exactly is using an ID selector preferred over a class selector when specificity is needed?

Theoretically, couldn't you use a class selector with a unique name (remembering to not assign anything else with that same class) to achieve the same result as if you would have used an ID selector? As far as I've seen, they do virtually the same thing. Is there some different benefit to using an ID selector, like for debugging purposes?

1 Answer

rydavim
rydavim
18,813 Points

You could use a class selector with a unique name. However, I think you've sort of answered part of your question when you said, "(remembering to not assign anything else with that same class)".

Sure, that's fine when you have a 3 page website with maybe 250 lines of code. But what about a much larger site? What about when you're working on updating a site from two years ago? What about when you're using vanilla JavaScript and need to select only that element?

Those are just a couple of things to think about when choosing between classes and ids. Happy coding! :)

Zach Robinson
Zach Robinson
8,862 Points

That makes perfect sense! Thank you!