Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS performance: descendent or two direct descendent selectors best?

Given the following HTML:

<ul>
  <li>
    <a ...

For the same set of declarations, which one of these two rule sets would be more advisable to use taking their performance into consideration?

ul > li > a {
  color: black
}
ul a {
  color: black
}
like image 944
alejandro Avatar asked Apr 21 '15 01:04

alejandro


1 Answers

The most fundamental concept to learn is this rule filtering. The categories exist in order to filter out irrelevant rules (so the style system doesn’t waste time trying to match them).

For example, if an element has an ID, then only ID rules that match the element’s ID will be checked. Only Class Rules for a class found on the element will be checked. Only tag rules that match the tag will be checked. Universal Rules will always be checked.

Avoid the descendant selector

The descendant selector is a more expensive selector than a child selector

BAD(Descendant selector)
sets the text color to black whenever an 'a' occurs anywhere within an 'ul' element

 ul a {
  color: black
}

BETTER Than above(Child selector)
'a' element must be the child of an 'li' element; the 'li' element must be a child of an 'ul' element

 ul > li > a {
  color: black
}

further reading LINK

like image 181
Alupotha Avatar answered Sep 30 '22 12:09

Alupotha