views:

46

answers:

2

I remember watching a video a while back online that was a talk given by an engineer at Yahoo and in it he mentioned that CSS selectors are read, by the browser, right to left and not left to right. Meaning #body .header .links a would actually pull out all anchors on the page filtering those with a parent of class links that had a parent of class header that had a parent with id body.

I can't find the video and was wondering if anyone has any references to reinforce this or is it not correct? Wouldn't this mean that something like #body .header .links li a is actually slower than just saying #body .links a? Assuming both work on a given page.

+3  A: 

I think this blog article goes into that direction: Simplifying CSS Selectors

The key to optimizing CSS selectors is to focus on the rightmost selector, also called the key selector (coincidence?). Here’s a much more expensive selector: A.class0007 * {}. Although this selector might look simpler, it’s more expensive for the browser to match. Because the browser moves right to left, it starts by checking all the elements that match the key selector, “*“. This means the browser must try to match this selector against all elements in the page. This chart shows the difference in load times for the test page using this universal selector compared with the previous descendant selector test page.

I haven't read through it in detail yet (it came to me as a recommendation) but it looks very good.

Pekka
A: 

When the browser matches the css selectors, it checks if each rule applies to a specific element. Therefore it's natural to validate selectors from right to left.

To check if the selector #body .header .links a matches the element, it first checks if it's an a element, then if there is a parent with the class links, then if that element has a parent with the class header, then if that element has a parent with the id body.

Guffa