CSS CSS Basics Basic Selectors Descendant Selectors

Why not just always use class instead of ID?

I understand that ID is for something you will only use once - and it has more weight than a class. But why not just use class every time? Is there any other reason to use ID? Would it be wrong to use only classes? Thanks

Usually classes are only used if there are more than one element which will take on the same class. Like (class="buttons") for of course buttons. Then an ID is a unique identifier, so for each button (id="submit-button"), (id="back-button") etc.

You don't have to have an ID for everything but you'll find it useful to target something specifically by using an ID. If you want one button to be red you cannot use class because then all the buttons would be red. Instead you'll go with (id="red-submit-button")

Thank you Joe Melon

1 Answer

Daniel Riches
Daniel Riches
19,691 Points

Id's come in handy for other things like automated testing, styling and manipulate the element or traversing the DOM with it. If trying to get a specific element, it's easier when it's unique. It's also less likely to change over time. If you have have to get something that only has a class on it, then you have to use a more specific selector, using things like parent elements. The markup might get changed and then the JS, CSS, Automated Test, etc. would have to be changed as well.