How Difficult Is It To Avoid Expensive CSS Selectors?

I’ve read all the articles and I’m still compelled to write rules like this one I wrote earlier tonight:

#main-menu .primary a{
	color:#7b0000;
}

I know I’m not alone in using rules like that. It’s a super common pattern.

It’s also very expensive because (surprisingly to most people I’ve spoken to) browsers read from right to left, first matching against the a in the rule (the “key”.) In certain documents, that obviously could generate a large number of elements to sort through, looking for ancestors that match the primary class and the main-menu id.

Part of the reason I’m sticking with rules like that is- I can’t actually imagine it being perceptibly expensive on the site I’m building (or for that matter, most of the sites I build.) This isn’t going to be a site with thousands of elements on a page, so I’m not going to stress about it.

The other part is the bit that’s going to make it difficult even when I am working on more intense application development. It simply feels right. I’ve been coding like that for so long and it’s so clearly convenient, I’m going to have a seriously hard time changing my method if the situation calls for it. We’ll just have to see how that goes when it comes up in practice.

Leave a Reply

Your email address will not be published. Required fields are marked *