Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an advantage to using very specific selectors in CSS?

I understand that in jQuery, it's advantageous to be more specific when using selectors so that jQuery doesn't have to traverse the entire DOM to find what you're looking for. For example, $('span.description') is better than just $('.description') if I know that the description class is only ever applied to <span> elements.

Is this the case with CSS, too? Is there any specific advantage for me to use span.description { } instead of .description { }? I'm thinking in terms of speed, optimization, etc. Am I saving the browser any work by telling it exactly where to look?

like image 429
Josh Leitzel Avatar asked Sep 13 '09 18:09

Josh Leitzel


3 Answers

This is true in CSS -

A good rule is to descend from the nearest ID. IDs are indexed so locating them is extremely fast. There is no reason to use more than one in your selector.

Google Code- Optimize browser rendering

This answered a lot of questions I had on the subject including this one- I hope you find it useful.

like image 79
Kelly Robins Avatar answered Oct 24 '22 22:10

Kelly Robins


Read up on css specificity - which is the most important reason to be more or less specific with your css.

http://www.w3.org/TR/CSS2/cascade.html#specificity

As browser performance is pretty much a non-issue (except for in jquery, as you've mentioned), my guideline is to be specific when you are controlling precedence, or when you want to make something a bit more readable in your css. Over specifying can make it tricky to re-use css selectors and make things overly complicated.

Edit

This looks like a bit of a duplicate:

CSS Performance Question

like image 29
ScottE Avatar answered Oct 24 '22 23:10

ScottE


it always depends on your amount of html code and the structure. It is definitely a good idea to use especially ids and appropriate selectors. (ie #nav li instead of li.nav). Since browser first load the html and then apply the css you are helping a lot.

This said, when it comes to pure css (no jquery) the difference in speed is nowadays not easy to distinguish, because the rendering engines are highly optimized - especially when it comes to applying css. So normally it shouldn't matter.

like image 37
Niko Avatar answered Oct 24 '22 22:10

Niko