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

HTML How to Make a Website CSS: Cascading Style Sheets Use ID Selectors

Brad Ward
seal-mask
.a{fill-rule:evenodd;}techdegree
Brad Ward
Front End Web Development Techdegree Student 351 Points

IDs over Classes

Hey there,

I just wanted to find out why you would ever use an ID over a class. In everything I've read and learned, I've basically been told to never use an ID, just use a class. Any insight on the differences, pros, and cons would be appreciated!

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

I'm no expert, but I'd say you'd use it for something that would always be unique. Let's say for instance that you have a site that sells a multitude of items. But only one item is ever going to be the "top seller" for that week. Now, it may be the same item 2 weeks in a row or more. But only one is ever going to be number 1. In that case, it might be nice to implement an ID to make sure that you don't accidentally mark two as the top seller. This, however, is the only concrete example I've thought up so far. Hope this helps! :sparkles:

Luke Towers
Luke Towers
18,572 Points

Most of the time, you'd be using IDs to make targeting an element in JavaScript easier, or if you wanted to link directly to that element through the addition of #element-id to the URL of the current page; i.e. using it for non-CSS purposes. You can even use it on form elements to improve accessibility through the use of labels with the 'for' attribute specified.

In terms of building HTML just to style it with CSS there really isn't a super strong reason to use an ID over a class, except for it to be a visual reminder to yourself that this particular element is unique as you're developing your CSS. It comes in handy though when you have to use an ID on an element for other purpose and you wish to target that element with CSS.