I spoke briefly about our particular CSS formatting structure in my last post. But here’s something else that’s been on my mind a lot.
At White Whale, we’re of course always thinking about code efficiency: less queries, less code, fewer requests, et cetera. And much of this on the design side is rote best practices (semantics, accessibility, compatibility). But I still find myself sweating more nitty-gritty details, so I was fascinated to see jpsykes’ analysis of this one. The question boils down to, “How specific should I get with CSS selectors?”
We have:
#header #navigation .portal { font-weight:bold; }
vs.
.portal { font-weight:bold; }
I’ve leaned toward the first on a gut feeling; .portal will only ever appear in #navigation in #header, so why not tell the browser where to look? But intuition is wrong in this case. Check out the graph (again, via jpsykes):

Giving more selector specificity causes performance hits across all the major browsers. What’s happening is that the browser actually starts at the right-hand side of the selector and searches backwards. So it finds all instances of .portal, then climbs up the DOM to make sure it’s in #navigation, then filters again for #header. (You’ll see that FF3 seems to perform best overall, but that’s a little misleading for reasons a commenter notes here. Check out the results with a better control.)
Interestingly, the opposite effect is true for JS frameworks. Their selector implementations — we use jQuery at White Whale — tend to process the selectors from left-to-right: first finding #header, then looking inside it for #navigation, and then inside that for any instances of .portal. So those work best when coded with some specificity.
It’s important to note here that we’re talking fractions of a second on a page with 20,000 test elements. So until we start serving 20,000 database records on a single page, our best practice will be whatever makes it easiest to keep the code straight in our own minds and for our clients — but I can’t help but think I’ll be subconsciously affected by the knowledge that every .newslist li .summary might shaving precious milliseconds off our load time.
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.