UX Design and Development course

Writing efficient CSS selectors


Efficient CSS is not a new topic, nor one that I really need to cover, but it’s something I’m really interested in and have been keeping an eye on more and more since working at Sky.

A lot of people forget, or simply don’t realize, that CSS can be both permanent and non-performant. This can be easily forgiven however when you realize just how little you can, err, realize, non-permanent CSS.

These rules only really apply to high performance websites where speed is a feature, and 1000s of DOM elements can appear on any given page. But best practice is best practice, and it doesn’t matter whether you’re building the next Facebook, or a site for the local decorator, it’s always good to know…

This is a particularly interesting article that discusses the priority of efficiency with selectors in browsers.

CSS selectors will not be new to most of us, the more basic selectors are type (e.g. div), ID (e.g. #header) and class (e.g. .tweet) respectively.

More uncommon ones include basic pseudo-classes (e.g. :hover) and more complex CSS3 and ‘regex’ selectors, such as :first-child or [class^="grid-"].

What is also of great reference is the descending list of efficient CSS selectors

  1. ID, e.g. #header
  2. Class, e.g. .promo
  3. Type, e.g. div
  4. Adjacent sibling, e.g. h2 + p
  5. Child, e.g. li > ul
  6. Descendant, e.g. ul a
  7. Universal, i.e. *
  8. Attribute, e.g. [type="text"]
  9. Pseudo-classes/-elements, e.g. a:hover

All in all, a great read that really helps get your head wrapped around what it means to write poor performing selectors. This isn't to say that you can't use some of these techniques, but just be aware that they may cause performance hits if used to much.

Do you need to care this much?

This also brings up another point. When the specification for how CSS is supposed to work and the implementation of that spec is done poorly, does this mean 'don't use that selector?' or does it mean, 'hey browser devs - stop sucking!' I vote for the browser devs to stop sucking!

This is an interesting topic raised by Nichole Sullivan and discussed in an article entitled CSS Selector Performance has changed! (For the better)

“My view is that authors should not need to worry about optimizing selectors (and from what I see, they generally don’t), that should be the job of the engine.”

~ Antti Koivisto