Rod
Rod

Reputation: 752

css performance with direct descendents

I searched but I don't get a concrete answer.

I will ask a simple question

Is it more effective to do this :

body > html > section > div.class1,
body > html > section > table > tbody > tr > td > div.class1 
{
    background-color : red;
}

or this :

div.class1 {
    background-color: red;
}

Upvotes: 1

Views: 49

Answers (2)

Nathanael Demacon
Nathanael Demacon

Reputation: 1217

Browsers will check and convert every code you give to them (HTML and CSS inclued), for each selector the browser set the attributes to the right HTML markers. For very small website it doesn't affect a lot but for large website like Amazon that have more than 1 million lines of code, it will affect a lot the performances.

I think this is a good exemple: https://www.html5rocks.com/en/tutorials/internals/howbrowserswork/#Main_flow_examples

Upvotes: 4

John Abraham
John Abraham

Reputation: 18781

Less specificity is faster. Every selector is another run of a loop. Rule of thumb, after 3 selectors deep perf will start to be impacted.

https://csswizardry.com/2011/09/writing-efficient-css-selectors/

Also note that well perf is in question, the real performance hit will be when you specify too deeply. I promise you that the long term maintenance become the real problem. Again 3 selectors deep is again a good Rule of Thumb.

Lastly, if you need help with css structure/architecture try:

1- http://getbem.com/

2- https://www.xfive.co/blog/itcss-scalable-maintainable-css-architecture/

Upvotes: 2

Related Questions