2

I understand that in nested CSS rules, the selector is applied from the most nested one, going bottom-up. For example in the following:

.foo > .bar .baz{
  ...
}

.baz elements are selected from the page, then it is restricted to those that are descendants of .bar, then it is restricted to those that are childs of .foo. Why does it work this way? I read that this is causing inefficiency in nested CSS rules. In most cases, I believe top-down restriction would be more efficient.

sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

4

The most efficient selector would require no traversal - it would simply apply to the element in question.

Whether you traverse from the top down or the bottom up it would be less efficient than no traversal.

Bottom-up is more efficient than top down because you only traverse where the selector matches - so if the current element is not .baz nothing more needs to be done. If it is a .baz you check ancestry for a .bar and repeat until you either fail a condition or match all the selectors.

Also, you are trying to work out whether to apply a style to the element, so you have one element and you determine matching styles. If you worked top-down you would be working on divergent matching, rather than convergent matching i.e. if you start at .foo you'll potentially find many matches for selectors to the right of the style rule - so you end up with trees of matching elements to check.

Fenton
  • 241,084
  • 71
  • 387
  • 401