Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of rules in a CSS stylesheet affect rendering speed?

While this could possibly result in a simple yes or no answer I'll go for it anyway


Consider the following example:

HTML

<html>
    <head>
    </head>
    <body>
        <div class="foo">
            <span class="bar">Hello world!</span>
            <p>Some really interesting text.</p>
        </div>
    </body>
</html>

CSS

html {
    /* some css */
}
body {
    /* some css */
}
div.foo {
    /* some css */
}
div.foo span.bar {
    /* some css */
}
div.foo p {
    /* some css */
}

Will the order in which css rules appear, have any effect on how (fast) the browser can render the page? ( in this example it won't really matter, but consider a real website with loads of html and css )

So the above css script will render faster or easier for the browser than :

div.foo p {
    /* some css */
}
div.foo span.bar {
    /* some css */
}
div.foo {
    /* some css */
}
body {
    /* some css */
}
html {
    /* some css */
}

Do browsers care? Should we?


Read before asking:

  • Is this how you would structure your CSS stylesheet?
  • What's the best way to organize CSS rules?
  • How do browsers read and interpret CSS?
like image 637
Willem Avatar asked Aug 04 '11 15:08

Willem


People also ask

Does order of CSS rules matter?

CSS Order Matters In CSS, the order in which we specify our rules matters. If a rule from the same style sheet, with the same level of specificity exists, the rule that is declared last in the CSS document will be the one that is applied.

Does the order of internal and external CSS matter?

The Order of CSS Classes in HTML Doesn't Matter.

What is the correct order of the CSS rule?

So the order is: position , float , display . Text is laid out in line boxes, then words, then glyphs. So properties for font-size and line-height come first, then text-* , then word-* .

Which rule has highest priority in CSS?

CSS specificity rule 1) Inline style: Inline style has highest priority among all. 2) Id Selector: It has second highest priority. 3) Classes, pseudo-classes and attributes: These selectors has lowest priority.


1 Answers

I can't speak to order of the rules as it relates to speed.

However, as CSS stands for Cascading Stylesheets I consider it a moot point as the order of your rules does matter. So you aren't necessarily at liberty to move them around freely. Unless of course you supply continually more specific selectors (i.e. html body div.foo), which I think would have performance implications. If nothing else in file size.

In the end, remember that premature optimization is the root of all evil. Furthermore, there are other things that will have greater effect on speed (minification, static domain, etc) than rule order. Not to mention there is something to be said for code readability.

like image 111
Jason McCreary Avatar answered Oct 22 '22 15:10

Jason McCreary