Would it be faster to use a CSS Child Selector?

2019-04-28 02:08发布

问题:

If we wanted to target a link within a paragraph, which selector would be more efficient/faster?

p a

or

p > a

回答1:

The second is (extremely) marginally faster. CSS is handled in reverse by browsers, so both your rules are tested on all a elements on the page. For the second rule it only needs to test the direct parent, for the other one it would need to test the entire descendant chain.

In practice, the execution time difference won't be statistically significant until you get tens of thousands of these on a page with just as many lines of HTML.



回答2:

Let me show you the efficiency order of selectors, from fastest to the slowest, that's some conclusion from google:

  1. id Selectors (#myid)
  2. class Selectors (.myclassname)
  3. tag Selectors (div,h1,p)
  4. neighbour Selectors (h1+p)
  5. children Selectors (ul>li)
  6. descendant Selectors (li a)
  7. star Selectors (*)
  8. property Selectors (a[rel="external"])
  9. pseudo class Selectors (a:hover,li:nth-child)

It might not be exactly right, and not being right for various of browsers, but still this order is available for reference. Hope it helps!

To see more about CSS performance, see: http://benfrain.com/css-performance-revisited-selectors-bloat-expensive-styles/