views:

48

answers:

2

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?

+2  A: 

Google's Page Speed recommendations explain how to write efficient CSS selectors: http://code.google.com/speed/page-speed/docs/rendering.html#UseEfficientCSSSelectors

gulbrandr
+3  A: 

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.

Pekka
+1 for raising the point regarding premature optimisation. CSS really could do with a selector "hint" that allowed you to say, in this case do "left to right" instead.
Paul Hadfield
It indeed is a dilemma. Will look at the google's page speed recommendations. Thanks
LochNess