Reputation: 829
Is div.container faster than .container ? You know like in jquery if you be more specific with your selectors it is faster since it iterates through less.. Is this the case with css ?
Is there a way to measure performance in css ? Performance wise, does things like this even matter or does it all depend on text weight basically ?
I'd be happy if someone knows the answer to it, I've actually found a similar question with no certain answer. Can CSS be more efficient if it is better specified?
Upvotes: 50
Views: 4959
Reputation: 13435
Generally, the fewer the rules the better, so .container would be faster than div.container. Apart from caching, the .container gets read first, then other elements have to have the div added on as a second-level filter... unnecessary in many circumstances.
This is pretty common across engine, though there are some minor deltas.
See this article: Writing efficient CSS, which although it is from MDN (and is therefore Mozilla-geared) holds true for most of what I know about the engines in general.
Upvotes: 5
Reputation: 3589
In real world the speed difference would be negligible.
To be technical .container
would be faster as it has fewer selectors to process.
Selectors have an inherent efficiency. The order of more to less efficient CSS selectors goes thus:
#header
.promo
div
h2 + p
li > ul
ul a*
*
[type="text"]
a:hover
In regards to your second question:
Is there a way to measure performance in CSS ?
Steve Souders put out an online test to measure performance of CSS that can still be accessed here.
There are better ways to measure performance nowadays, but this is a quick and easy resource you can play with.
Performance wise, does things like this even matter or does it all depend on text weight basically ?
The short answer is "not really".
The long answer is, "it depends". If you are working on a simple site there is really no point to make a fuss about CSS performance other than general knowledge you may gain from best practices.
If you are creating a site with tens of thousands of DOM elements then yes, it will matter.
Upvotes: 52
Reputation: 1856
delta between the best case and the worst case was 50ms. In other words, consider selector performance but don’t waste too much time on it. See: https://smacss.com/book/selectors
So I do not think it makes much sense to extend CSS rules ONLY to get a higher performance. Just consider the higher amount of network traffic, maybe worse maintainability, ... However in the link you can read, which rules to consider without having to increase the CSS size.
If .container and div.container match exactly the same elements on your page, the first one might be even faster: If the browser evaluates .container at first, actually it would have been finished, but with div.container it has ADDITIONALLY to check, whether the element is a div.
disclaimer: I do not know how browsers really implement these things. My conclusions are based on the linked article.
Upvotes: 4