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 Introduction to HTML and CSS (2016) Getting Familiar with HTML and CSS Welcome to HTML and CSS

Rex Irvin Carpen
Rex Irvin Carpen
3,314 Points

Why use class rather than id, when naming a selector?

I usually use id when naming a selector. I wanna know is there difference when using class instead of ID?

2 Answers

Raja Kannan
Raja Kannan
6,590 Points

Hi,

ID's are unique *Each element can have only one ID *Each page can have only one element with that ID

Classes are NOT unique *You can use the same class on multiple elements. *You can use multiple classes on the same element.

Rex Irvin Carpen
Rex Irvin Carpen
3,314 Points

Hello Raja . Thanks for the answer, follow up question. Can you use ID and class at the same time?

Ari Misha
Ari Misha
19,323 Points

Hiya there! The convention is you can only use id once per element whereas you can class multiple times for multiple selectors or for/within the same selector as well. I mostly use id for my main container divs and maybe few inputs. But i use classes for the selectors that might repeat itself on the same page or in the same container div.

~ Ari

Rex Irvin Carpen
Rex Irvin Carpen
3,314 Points

tnx Ari so class is more efficient in repeated the same selectors.

Ari Misha
Ari Misha
19,323 Points

Both are efficient ad you can implement 'em in your own way or convention. Use class for selectors which will repeat itself a lot. Moreover, you'll end up using classes more than ids anyway.