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

Why use id instead of class?

I've wondered this for a while. An id selector can only be used once on a page, a class selector can be used multiple times. Why use id at all, when class isn't limited in the same way? Does anyone have some unique examples of when using an id would be preferable to using a class?

2 Answers

This article helped me when I was starting out and has some very good information.

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

Also to what Mr. O'Connor stated ID's and classes mean nothing in css. The only place ID's have more abilities is in the browser.

This article is great! Thank you so much for the resource. It gave me the larger context that IDs and classes exist within.

One example from that article about when to use an ID:

  • When you want to link to a specific element on a page, use an ID. You can then link to it like this: www.some-site.com/cool-blog-post.html#comment-252. (The hashtag tells the browser to immediately scroll down to the element with the ID "comment-252" upon arrival at that page.)

IDs are usually used when you need to reference that element in JavaScript, so if you were looking to fade out a div when a button is clicked the div and button would get IDs instead of classes. So I use IDs for reference and classes for styling ... most of the time.

I'm (almost) sure IDs have more specificity in css than classes do, but don't quote me on that right now ... :)

There are multiple ways to select HTML elements in JavaScript without using ID's. Using jQuery allows for selection by class, tag, and more. In your example, you could use classes like "js-fade-trigger" and "js-fade-out" and reference them from JavaScript using jQuery.

I recommend only using ID's for unique identification of elements on the page when it's required. E.g. "comment-257" on a blog post so people can link directly to that comment when they share it.

I believe you're right about the specificity of ID's, though. Another good reason to avoid using them for styling.