Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector speed

According to new article from css-tricks there is a big difference between how you select your elements because they are selected from right to left.

The article can be found here. http://css-tricks.com/efficiently-rendering-css/

I am about to create a page that have different documents on the same page:

My question is, how should i go about the HTML for CSS efficiency or vise versa?

<div class="document-type-1">
    <h1>Some heading</h1>
    <p>Some paragraph</p>
</div>

<div class="document-type-2">
    <h1>Some heading</h1>
    <p>Some paragraph</p>
</div>

There can be multiple of the same document type, i can therefore not use an ID.

.document-type-1 h1 {

}

.document-type-1 p {

}

.document-type-2 h1 {

}

.document-type-2 p {

}

This will be "inefficient" since all p tags are found first...

How would you go about it if this should be done faster and you should be able to move the same article to a new document type?

like image 696
LochNess Avatar asked Oct 28 '10 10:10

LochNess


Video Answer


1 Answers

As far as I can see, if I understand the article correctly, the most efficient way to do this - if you don't use a custom ID for each element - would be:

// YUCK!

<div class="document-type-1">
    <h1 class="document-type-1-h1">Some heading</h1>
    <p class="document-type-1-p">Some paragraph</p>
</div>

.document-type-1-h1 {

}

.document-type-1-p {

}

But this is disgusting. It is a dilemma that writing perfectly efficient CSS goes against all rules of writing good CSS.

Unless there are real, actual rendering speed problems caused by CSS rules, I would tend to obey some common-sense rules (e.g. not being wasteful with global selectors > * style, not using "overly qualified selectors" like form#UserLogin {...}, not using too many rules in general....), but otherwise focus on clean, well structured CSS. As the article itself states:

I think the lesson here is not to sacrifice semantics or maintainability for efficient CSS.

The Google Page Speed tips linked to by @gulbrandr in his answer give some good real-world advice.

like image 71
Pekka Avatar answered Sep 19 '22 14:09

Pekka