Keavon
Keavon

Reputation: 7493

Best practice/performance between descendent and direct descendent selectors

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

Answers (2)

Keavon
Keavon

Reputation: 7493

Answering strictly in terms of performance, I found this reference that ranks child selectors as having better performance than descendent selectors.

  1. ID, e.g. #header
  2. Class, e.g. .promo
  3. Type, e.g. div
  4. Adjacent sibling, e.g. h2 + p
  5. Child, e.g. li > ul
  6. Descendant, e.g. ul a
  7. Universal, i.e. *
  8. Attribute, e.g. [type="text"]
  9. Pseudo-classes/-elements, e.g. a:hover

Upvotes: 0

David-SkyMesh
David-SkyMesh

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

Related Questions