views:

209

answers:

5

Does anyone have information on browser selector speeds in CSS? In other words, how different selectors compare to each other (in th same browser).

For example, I often see (and write) code like this:

#content #elem { ...rules... }

But since those elements are unique IDs, I should only need #elem, right? This got me thinking about whether maybe it's quicker for browsers to have more complex selectors - my thinking being that a browser might find #content and know to only look in that element, no where else.

Another example might be table tr td .class vs table .class

+3  A: 

There could be a difference in speed but in its not perceivable in any normal usage case. The real reason to write your CSS like that is specificity. That is if you have

#content #elem {color: black;}

and

#elem {color: red;}

The element should be colored black since that is the more specific rule.

Jason Christa
Or, more generally, the reason for writing such code is that sometimes you want the same element to appear different based on where in the document it lives.
gnud
+2  A: 

To be honest, you're talking such a small amount of time that I don't think it really makes a difference.

In terms of using more specific selectors - I think this is good practice for a couple of reasons:

  1. It enhances code readability - at a glance can see more where you're selectors are being applied relative to the HTML.
  2. It reduces the likelyhood of your selectors being overwritten somewhere else, as a selector with even more specifity would have be written which is very unlikely to happen.

What you're talking about may make a difference when using JavaScript libraries such as jQuery - as they have to parse the whole document themselves, but I've certainly never noticed any speed differences myself.

wows
+2  A: 

Not to be a wise guy, but the time it took you to write that question probably exceeds the sum of all time savings of all the users that will ever visit your site (in relation to #id #id2 vs #id2). So does the time to write this answer....

you may vote me down now :)

Darko Z
+2  A: 

Here is some info I got after a quick search .

Angel Chiang
+2  A: 

Mozilla's guidelines might be interesting.

Ms2ger