Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS child vs descendent selector

I read that using the child selector (>) in css is faster than the descendant selector (). For example: p > em as opposed to p em.

It seems to me that the majority of code I see in the wild does not take advantage of this.

I understand that certain circumstances would merit the use of one or the other, but in general, Should I be striving to take advantage of the child selector whenever possible? Or should I follow what seems to be convention and rely mostly on the descendent selector?

like image 936
Zach Lysobey Avatar asked Aug 27 '10 02:08

Zach Lysobey


1 Answers

Theoretically the child selector will be faster than the descendant selector because the browser can stop checking child nodes after the first level. However, I suspect that any performance enhancement you see from this will be negligible as browsers parse CSS quickly in the first place.

As NullUserException pointed out, the selector doesn't work in IE6, so if you care much about IE6 I wouldn't load your CSS with it. But a good thing to keep in mind is that you should have a very clear idea of which to use in which situation. Ask yourself, "do I want this declaration to cover all matching children, or do I want it to cover only direct matching children?" It may seem obvious to ask yourself such a question, but it really is the only way you should choose between the two. Don't use > unless you mean it.

Also see my question Is there an advantage to using very specific selectors in CSS?

See also: CSS selector support per browser

like image 101
Josh Leitzel Avatar answered Oct 04 '22 03:10

Josh Leitzel