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
Max Bergman
1,004 PointsCSS- Class selectors, which one to use?
The course didn't really define which one to use specifically in a real world situation? For example why would I use an ID selector instead of a class selector etc. Can someone give me a general paragraph I can refer to as a generalization general?!
1 Answer
Darrell Osborne
23,146 PointsI agree with everything Travis posted.
One more thing to add is that it may become more clear when you start learning JavaScript. ID's are extremely useful when selecting a specific element for use with a JavaScript action/behavior.
Travis Batts
4,031 PointsTravis Batts
4,031 PointsSo when thinking about classes and ID's the important thing to remember is that an ID is in reference to only that one element. Where as classes can be used on different elements. So here is a quick example..
<div id="features" class="flex-container">
</div>
So this ID should only be used once that's it. Where as this flex-container I can call this in another div like this.
<div id="testimonials" class="flex-container">
</div>
The benefit of having multiple classes is if I'm styling a div that uses the same flex-box layout I can just call the class on each div container. So style your class (.flex-container) in your css style sheet and then place it in the html wherever you deem fit.
But If I want to have a different style for the background or perhaps change some of the content inside the div. I would place an ID and that would only pertain to the div the ID is referenced to..
Also just remember an ID takes precedence over a class when styling. So if you're not careful and do something like this in your css ..
#features p { color: red; }.flex-container p { color: purple; }The ID will always take precedence over the class. There is also a lot more to learn about CSS precedence, but I just wanted you to realize that an ID is more specific than a class in your CSS sheet.