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 trialodysseywow
2,783 PointsID selectors vs Class selectors
When should I use an ID selector as opposed to a Class selector? Class selectors seem like the better option, but I am sure that there's reasons for the use of an ID selector, otherwise it wouldn't exist anymore.
1 Answer
Jonathan Grieve
Treehouse Moderator 91,253 PointsHi there.
It's right to say that class selectors are more commonly used.
There's a couple of things to consider. ID Selectors have a higher specificity than class selectors. By definition, ID selectors give an element a Unique selector. It can only be used for that specific element. That's not to say that you can't give an element both an ID and a class selector, but if you're using the same styles in that selector the ID styles would override the Class styles.
Contrary to the ID selectors, you can use Class selectors on more than one element... which is useful for doing things like styling multiple article entries in a blog.
I like to use an ID selector on something like the <main>
element as most websites I like have one containing element.... such as a main
or a div
element.
So, for me, it's not one being selectors being better than the other. It's about understanding the benefits and limitations of each.