I wonder, if there is a difference of getting every direct child in css between
tag > *
and
tag > :nth-child(n)
I know that the universal selector is slow, but I don't know, what the nth-child selector is doing under the hood.
I wonder, if there is a difference of getting every direct child in css between
tag > *
and
tag > :nth-child(n)
I know that the universal selector is slow, but I don't know, what the nth-child selector is doing under the hood.
I know that the universal selector is slow
No, the universal selector is fast, because it does nothing except guarantee a match (there are rare exceptions but they don't apply here). The only time it's "slow" is when you have a page with a ridiculously large number of elements (in the order of thousands) — then the browser has to run it on every element to determine if it's a child of whatever parent.
Using :nth-child(n)
is needlessly asking the browser to evaluate an n
expression as opposed to immediately matching the element no questions asked. Even if a browser did optimize away :nth-child(n)
, you're left with a guaranteed match exactly the way *
works. So you're really just wasting space by using :nth-child(n)
(12 whole bytes longer than *
), and not getting any computational gains out of it versus just using *
.
Just stick with the universal selector. Or, if you're that worried about CSS selector performance, you can always add a class name to every desired child element and select that class instead, at the cost of markup bloat.
The only functional difference between *
and :nth-child(n)
is specificity — the specificity of *
is zero, which is less than a pseudo-class. You generally never need the extra specificity, so again, there is no reason not to stick with *
for this use case. See my answer to this question for a specificity-centric use case.
Take a look at the w3school the :nth-child() selector is for select an specific child, but if you want to select everything from the container, use the * selector. In the case of using :nth-child(n), is the same as using the * selector, and the * uses less space.
Wonder it helps.