In CSS I need to select all the direct children of an element with the class foobar
. The obvious way would be to do this:
.foo > * {
foo: bar;
}
There are some similar questions on Stack Overflow, but I don't think this question is a duplicate. The question simply asked how to select all direct children of an element. The answer said to use something like what I showed above. But a comment there and a comment elsewhere claim that this approach is extremely inefficient, claiming that the *
selector would result in all elements being selected before the child selector took effect:
Be aware that this is an extremely inefficient selector! Css selectors are validated from right to left so by using the asterix (*, aka universal selector) at the end of the selector the browser will select all elements and then starts filtering further (in this case: only the elements that are direct children of the 'body' element). So for small pages this would not be an issue but in larger single page apps it can slow things down...
(Frankly this sounds suspicious to me; are browser selection algorithms really that non-clever?)
So this question is different: how then do I make an equivalent selection that is efficient?
Do I do this? (Note that I updated this option; I like using :root
because I don't have to introduce any dummy elements.)
.foo > :not(:root) {
foo: bar;
}
Or do I do this?
.foo > :nth-child(odd), .foo > :nth-child(event) {
foo: bar;
}
Are those really more efficient than .foo > *
? Do you have a better suggestion?
(In my particular use case, there will only be around two or three children, but the entire document could be large.)