In Defence of CSS IDs

August 19th, 2011

Thanks to current best practices the use of CSS IDs has been scorned and mocked apart from when absolutely necessary. I'm all for objects in my CSS and reusing code but there are a few things to say for the humble ID before we throw it by the wayside.

Speed

It's probably not the first thing you think of when you consider CSS, but IDs are the fastest selector according to this study. Although it's more a case for devices with slower processors, if you have a large site with an object-oriented CSS file it might render slower than one with a healthy amount of IDs and classes.

Usefulness

It has to be said, IDs can come in fairly useful to quickly target an element when mocking up a design or even outlining wireframes for clients to give them a better idea of what content will be there.

It works well with JavaScript

getElementById() is probably the easiest way to start manipulating the DOM and therefore is extremely useful. There is of course getElementsByClassName(), but this doesn't work in IE 5.5 - 8, so you can't rely on it without using an external JavaScript library that will add the functionality. Of course, if you don't want the extra heft then the simplest solution is to add an ID!

These are the three main reasons I don't think we should abandon the ID selector just yet, and perhaps should be more forgiving to those that use it extensively. Myself, I've been playing devil's advocate and try to write object-oriented CSS in my projects because of its many practical benefits but it's worth keeping in mind and questioning why you're doing something, rather than doing it because you've been told you should.


About the Web. There are no comments (yet!).