Speed/redundancy of selectors in CSS [closed]
-
03-07-2019 - |
Question
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
Solution
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:
- It enhances code readability - at a glance can see more where you're selectors are being applied relative to the HTML.
- 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.
OTHER TIPS
Here is some info I got after a quick search .
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.
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 :)
Mozilla's guidelines might be interesting.
There is always some choice between efficiency and readability. Of course
table tr td .class
is most readable, but very inefficient and can be simplified - do you have seen anywhere (assume valid markup)tr
withouttable
ortd
withouttr
? At least you can comment redundant part like:/* table tr */ td .class { color: #ccf; }
Sometimes as others mentioned you need additional specificity, e.g. your
#elem
should be red everywhere except when in specific context of#content
.#elem { /* usually red */ color: red; } #content #elem { /* except when in specific context */ color: black; }