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 Selectors

Tati Gvozdik
Tati Gvozdik
746 Points

I do not understand the meaning of use ID selectors. What is the use of them if you can replace them with Class?

And I understand the differences between them. But what is the advantage of using ID selectors?

2 Answers

Hi Tati,

normally you only use class-only, because css doesn't really matter. However, Id is later important for Javascript - for example the getElementById. to find out more you can have a look at this. https://css-tricks.com/the-difference-between-id-and-class/

Best regards - Phil

Kevin Korte
Kevin Korte
28,148 Points

I love CSS Tricks, but the statement that made that CSS doesn't care, isn't true. CSS does care if you use a class or an ID when it comes to selector specificity. I see a lot, including myself, but especially newer developers not understanding why their CSS is doing something they weren't expecting, and it is often related to the specificity of one rule is overriding another.

In a later article, CSS Tricks talks about CSS specificity, which is a great article, and should also be read: https://css-tricks.com/specifics-on-css-specificity/

Because of this, I use classes as my default. I leave ID selectors to Javascript and/or ways to help ensure that the selector should end up overriding competing selectors made of classes. I always try to keep my specificity as low as possible.

Yes Kevin, that is of course true. I meant that you can decide for yourself if you use class or id. Css will accept both. Of course you have to be aware that Id has a higher rank and must be unique. That's why I attached the article.

Kevin Korte
Kevin Korte
28,148 Points

I'm not saying you were wrong at all, I was just adding to the discussion. I like you, use classes for styling, and try to reserve ids for javascript usage.

While the article is good, and I love CSS Tricks, that particular one didn't mention anything about CSS specificity, which is why I linked the second for further reading.