alejandro
alejandro

Reputation: 409

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
}

Upvotes: 8

Views: 1111

Answers (1)

Alupotha
Alupotha

Reputation: 10093

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

Upvotes: 7

Related Questions