The problem with ID’s in CSS

Despite all the discussion on this topic, there are still people who insist using ID selectors in their stylesheets is perfectly OK. I'd like to once and for all demonstrate why using ID's in your stylesheets is a bad idea.

The other day I had a back-and-forth on Twitter with a friend of mine regarding the use of ID's in CSS. This pretty much sums it up:

The problem with this attitude is that in every practical sense avoiding ID's in CSS is common sense, and pretending it's some sort of hype to be avoided will land you in a clusterfuck once you need to reuse styles or move a module from sidebar to footer.

The problem with specificity

#footer a { color: red; }
.calendar { background: red; color: white; }
.calendar a { color: inherit; }

A common scenario. You want all the links in your footer to be red. No biggie, right? Until you want to shove your red calendar background in there, with white text and links. Immediately you'll see that you've made a huge mistake. The links in the calendar inherit the color from the #footer links, because an ID style has 256 levels of specificity. In other words you'd have to add 256 classes to your calendar link style to override the footer link color. Or you can just add an !important. But do you really want to start adding !important clauses into your stylesheets just to keep using ID's?

The problem with modularity

#calendar { background: red; color: white; }
#calendar a { color: inherit; }

Looks innocent, right? As long as you can absolutely, definitely guarantee that the calendar will only ever appear once in any single page, you won't find this problematic (except for the specificity issues when you want to add a module inside the calendar). But clients are clients, and this specific client has just asked you to put the calendar in the sidebar AND the footer. The calendar is surprisingly important to your client.

So what do you do? Add another calendar called “calendar2″?

#calendar, #calendar2 { background: red; color: white; }
#calendar a, #calendar2 a { color: inherit; }

Hopefully you see the problem with this. All this just to avoid using a class on the calendar.

So what should we do?

The solution is the easiest thing in the world and it won't hurt your self respect one bit. Just target the elements you want to style using classes.

If you're used to doing this:

#header nav a { color: red }

Do this instead:

.site-nav a { color: red }

Or this:

.site»nav›link { color: red }

You won't have to override anything using !important rules, you can decide to move or copy the entire block to the footer or sidebar without redoing your styles, you can do whatever you want and you'll ask yourself why you were ever using ID's in your CSS.

Comments? Tweet me!