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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With