After hacking apart & cleaning up code for the better part of the day, I’ve decided to set the record straight about CSS, IDs, and Classes. The question is “when should I use an ID, and when should I use a class?” Is it that big of a deal?
Why does it matter? Because an ID and Class have one major difference:
ID is supose to be 100% unique to a single HTML element through the entire HTML document. Class can be shared among many elements.
This is using an ID
This is using a class
So when should you use ID and when do you use a class? Here is my rule of thumb:
Unless you are 100% sure that you will never, ever have a duplicate element name on the same page, use a class. When in doubt, use a class. Only use an ID when you’re positive it will always be unique.
Examples of when I would use an ID are:
- Unique parts of page layout:
- Identifying specific items:
If it doesn’t fall into those two categories, I usually won’t use an ID. Most of the time, I’ve never had moment where I wished a developer had used a ID instead of a class. But I’ve had many times where I wish an element used classes intead of ID.