IDs and classes are both used in CSS to select (hence the name “selector”) items you would like to add styles to. However, that’s about where the similarities end.
So how are IDs and classes different?
IDs are unique to a document, classes aren’t
Most people know this by heart because someone already drilled it into them. IDs are unique to a document, while classes don’t have to be. What’s this mean?
So lets pretend for a second we’re not talking about page elements at all, lets say, we’re talking about people in a classroom. So if I say, “Sarah Yates, please come to the front of the room.” I’ll only get one person this is like what happens when you use an ID to select an item. Conversely, lets say I asked, “Can all the females come to front of the room?” I’ll get all people who fit that description, this is like using a class selector.
So, in context, you can only have one id in a document with the value of “header”, and you can have multiple classes in a document with the value of “widget”.
Two is Better Than One?
You can declare multiple classes in one tag class attribute, you can’t declare multiple ids. So for instance:
<div id=”header” class=”class1 class2″></div>
Just remember to declare the multiple classes with a space in between them. Otherwise, neither class will show up.
Developers Love Their IDs
IDs are used in a variety of back-end languages, so be careful when naming or using IDs that you’re not stepping on your developer’s toes. If you’re working with a back-end developer make sure to talk to them about how they use IDs in their code and come to a consensus as to how you’re going to effectively share ID attributes.
But, when do you use which one?
Is this styling appearing on a page only once EVER?
When planning out CSS style selectors, I go with this one major rule. If the answer is yes, using an ID is appropriate, but if you’re planning on using the styling more than once, say for instance, you plan on having more than one “widget” per page, then use a class.