Would it be faster to use a child CSS selector?

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

p a

      

or

p > a

      

+3


source to share


2 answers


The second is (extremely) marginally faster. CSS is processed in reverse order by browsers, so both rules are checked on all elements a

on the page. For the second rule, you only need to check the direct parent, for the other, it will have to check the entire chain of descendants.



In practice, the difference in execution time won't be statistically significant until you get tens of thousands of them on a page with the same number of lines of HTML.

+7


source


Let me show you the order of effectiveness of selectors, from fastest to slowest, some output from google:

  • id Selectors (#myid)
  • Class selectors (.myclassname)
  • Selectors tags (div, h1, p)
  • neighbors Selectors (h1 + p)
  • children Selectors (ul> li)
  • Descendant selectors (li a)
  • Selector selection (*)
  • Selecting properties (a [rel = "external"])
  • Pseudo class selectors (a: hover, li: nth-child)


This may not be entirely correct and does not work across browsers, but this order is available for reference. Hope this helps!

For more on CSS performance see: http://benfrain.com/css-performance-revisited-selectors-bloat-expensive-styles/

+4


source







All Articles