Reputation: 7493
I'm wondering about the best practice and performance between using a descendent selector or a direct descendent selector. In the first case shown in the HTML below, both selectors would work equally because there is only one child.
<div>
<p>Foo Bar</p>
</div>
In the markup above, is div p
or div > p
better practice/performance?
In the HTML below, there are several children elements.
<div>
<p>
<a>
<span>Foo Bar</span
</a>
</p>
</div>
Assuming the desired target is the span tag, is div span
or div > p > a > span
better practice/performance?
Upvotes: 2
Views: 339
Reputation: 7493
Answering strictly in terms of performance, I found this reference that ranks child selectors as having better performance than descendent selectors.
- ID, e.g.
#header
- Class, e.g.
.promo
- Type, e.g.
div
- Adjacent sibling, e.g.
h2 + p
- Child, e.g.
li > ul
- Descendant, e.g.
ul a
- Universal, i.e.
*
- Attribute, e.g.
[type="text"]
- Pseudo-classes/-elements, e.g.
a:hover
Upvotes: 0
Reputation: 5171
Don't think about CSS performance. It's almost certainly a premature optimisation. If it's not premature now (i.e: not really a meaningful performance consideration), it will be in the near future (i.e: will be optimised well enough by browsers covering the vast majority of your target demographic).
The difference between a b
and a > b
is the level of "specificity" how deeply the selector engine must search to match b
starting from a
. While this might have an effect on performance (for large counts of elements matching a b
), the a > b
case might mean you'll lose flexibility in design.
In this case, if you attempted to 'optimise' performance by changing all cases of a b
to a > b
, you'd lose the ability to easily add more layers of DOM elements between a
and b
in your design without changing your CSS a lot. Leaving it less specific allows you to design in terms of 'behaviours'.
Also, while a > b
(theoretically) does less work than a b
, in most cases judicious use of classes on both levels will be equivalent (i.e: a.x b.y
).
edit: Incorrect use of term specificity
css-wise, and potentially incorrect algorithmicly. Better to state in terms of matching.
Upvotes: 5