Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference in performance between the child and descendant selectors?

I can write the CSS selector using the child combinator > or just a space indicating any descendant. For example, I have this HTML code:

<span id='test'>
    <a href="#">Hello</a>
</span>

And I can write my CSS code in the following two ways:

#test > a {
    ...
}

or

#test a {
    ...
}

What is the best way, regarding the performance, to write the following CSS code?

like image 215
mikelplhts Avatar asked Jan 07 '23 20:01

mikelplhts


1 Answers

Browsers parse selectors from right to left.

Then if you use #test > a, for each a element in your page, the browser checks whether its parent has id="test".

But if you use #test a, for each a element in your page, the browser checks if some of its ancestors have id="test". There shouldn't be many of those elements in the document, so probably the browser will have to check all ancestors of each a.

I haven't done any tests, but I expect checking all ancestors is slower than checking only the parent.

So probably #test > a is faster.

like image 106
Oriol Avatar answered Jan 09 '23 11:01

Oriol