CSS Tricks: How to Speed Up CSS Rendering

CSS Tricks: How to Speed Up CSS Rendering

When coding CSS, one of the best ways to ensure your code runs smoothly on older browsers and slow computers is to write your CSS efficiently for browser rendering, this way your site takes less resource and memory from the user’s computer and therefore runs smoother.

Browser vendors constantly trying to make rendering faster, the faster pages load the happier people are using their products. Google is always on a crusade to make the web faster. Mozilla also has several articles about best practices.

In this posting we cover some of the big ideas they present, and then discuss the practicalities of it all.

CSS Tricks: How to Speed Up CSS Rendering

Ways to Speed Up CSS Rendering

Avoid reflow and repaint by specifying image dimension

To avoid unnecessary reflows and repaints, always specify a width and height for all images, it allows the browser to render the page even before images are downloaded, otherwise the browser will require a reflow and repaint once the images are downloaded. You could specify the width and height of all images, either in the HTML img tag, or in CSS. If you need smaller images, scale it in an image editor and set its dimensions to match, avoid using width and height specifications to scale images on the fly.

Universal Selectors are the Least Efficient, ID’s are the Most

Here are selectors according to rendering speed:

#sidebar  {}       	     /* ID (Fastest) */
.home #slider {}         /* ID */
.footer {}               /* Class */
ul li a.arrow {}         /* Class */
ul {}                    /* Tag */
ul li a }                /* Tag */
* {}                     /* Universal (Slowest) */
#content [title='home']  /* Universal */

For example this selector isn’t very efficient:

#sidebar > li

Since IDs are the most effective, you would think the browser could just find that ID quickly and then find the li children, but it won’t speed up the rendering speed since browsers render selectors right to left.

The Principle of Right to Left
It’s very important to understand how browsers read your CSS selectors. They read CSS from right to left so the selector ol > li a[title="link"] the first thing interpreted is a[title="link"] (it is also referred to as the “key selector”).

It’s good to know that as soon as the right-to-left interpretation of a selector fails a match, it stops trying, and so expends less energy than if it needed to keep interpreting. However, you should always remove unused selectors in your code.

Move link Elements from the Document Body to the Document Head

Always put external CSS and style blocks in the head section. Specifying external stylesheets and inline style blocks in the body of an HTML document can take much more time for the browser to render the document.

Descendant Selectors

The most expensive selector in CSS is the descendant selector. It is terrible expensive, particularly if it is in the Tag or Universal Category. For example, a selector like this is a very bad choice:

html body nav a span {} 

Take Advantage of CSS Cascade

Sometimes you can achieve your desire result without using extra selectors. For example consider this code:

nav li a {font-size:14px}

Since font-size cascades, you don’t need to specifically declare your CSS and it is far more efficient:

nav {font-size:14px}

Overly qualified selectors

Don’t do this:

form#UserLogin {}

ID selectors are unique; it just makes them less efficient as they don’t need a tag name to go along with it. Classes aren’t unique, but it’s a good idea to avoid this method on classes too.

CSS3 Selectors

CSS3 selectors (e.g. :first-child) are amazing in helping us style the elements while keeping our code clean and semantic. But in fact these fancy selectors take more browser resource to use. The sad fact about these selectors is that you shouldn’t use them at all if you care about page performance.

Speed vs Practicality

To achieve the most efficient rendering for a given page, one might simply go overboard giving every single element on the page a unique ID and applying styling with single ID selectors. It is extremely non-semantic and extremely hard to maintain. Even hardcore performance based sites don’t sacrifice maintainability or semantics for efficient CSS.

You could as well follow them, but you shouldn’t to be all dogmatic about it. It may be worth revisiting your CSS and look for where you can do better especially if your target audience is mostly on mobile devices with limited computing power, this can be a lifesaver, otherwise don’t worry about it.

Conclusion

These best practices require some upfront investment, but the cost is small – especially in comparison to the gains. And once these improvements are put in place, they continue to boost performance over the life of the development process. I hope you’ll find these rules to be elegant improvements that benefit you and your users.

Between web design and development, UX freelancing, writing, and android programming, Faraz Karimian has an increasingly hard time deciding what to say in short bios.

Comments

  1. / Reply

    It’s good to get a reminder of these things especially pseudo elements.

    I am surprised that pseudo elements are included in the right to left rendering of CSS (though I have always assumed this to be so). I can’t help thinking that :after, :nth-child etc would be more efficient if saved til the end of each rules processing.

    For example
    .nav li a:first-child
    would instead be rendered as a then li then nav and then finally find the first child.

    If anyone knows why making an exception in the order for pseudo elements wouldn’t be a good idea I would love to know why.

  2. / Reply

    CSS speed is mostly irrelevant now anyway… computers are wicked fast and the rendering engines keep getting better…

    http://paulirish.com/2012/box-sizing-border-box-ftw/

    http://calendar.perfplanet.com/2011/css-selector-performance-has-changed-for-the-better/

    (just sayin)

    1. / Reply

      Indeed, computer processing speed has increased, but this isn’t irrelevant by any means. Regardless of rendering engines and processing speeds, writing clean and semantic style sheets is just as important as ever.

      Imagine having multiple style sheets with hundreds of lines of code, while your site is receiving heavy traffic. That is a lot of unnecessary HTTP requests, which DOES slow down page speed. Maybe for smaller sites, you can get away with unorganized CSS. Page speed is more important than ever as now Google uses it as part of its algo as well as user experience.

      No web designer/developer should turn their nose up at this advice and throw it away so easily. This is excellent advice.

        • Kitop,
        • May 4, 2012
        / Reply

        How ironical if we should ignore CSS speed. It’s like saying we should not maintain our computer since they are fast and powerful.

        I agreed with Michael, that by optimizing CSS, we can improved the speed and it will be easier for site maintainance.

        1. / Reply

          I tend to go with Paul Irish on this one…

          “Aside from that, you are not allowed to care about the performance of * unless you concatenate all your javascript, have it at the bottom, minify your css and js, gzip all your assets, and losslessly compress all your images. If aren’t getting 90+ Page Speed scores, its way too early to be thinking about selector optimization.”

          There are bigger problems on your site that you need to fix before you optimize away the css. The same goes for code:

          for may be faster than foreach, but it is not worth optimizing it out before fixing your database usage and adding static code caching.

            • John Reeve,
            • May 6, 2012
            /

            “There are bigger problems on your site that you need to fix before you optimize away the css. ”

            Indeed: if there is in fact a tradeoff between writing readable/logical/semantic css and performance, the better strategy is to stick with readability. Not only are there numerous other, easier to implement optimizations, but my feeling is that if you balance the cost of maintaining code vs. the cost of not optimizing your CSS selectors (in terms of converstions or whatever metric you are using), you’ll find that it’s cheaper to not optimize.

            And that’s even -if- rendering speeds are an issue.

        • Oliver Turner,
        • May 6, 2012
        / Reply

        > “Imagine having multiple style sheets with hundreds of lines of code, while your site is receiving heavy traffic. That is a lot of unnecessary HTTP requests, which DOES slow down page speed.”

        True… but not relevant to the point that was being made: _rendering_ speed is barely affected even by inefficient targeting because modern browsers are so fast.

        The more salient issue is that efficiency _does_ come into play in the context of vastly less powerful mobile browsers.

        > No web designer/developer should turn their nose up at this advice and throw it away so easily. This is excellent advice.

        Agreed.

      • anders,
      • May 4, 2012
      / Reply

      Smartphones are not quite as powerful as your main computer (yet).

      • Sebastien Paquet,
      • May 5, 2012
      / Reply

      as Steve Souders also said somewhere, It mostly matters on big sites.

    • Scott,
    • May 3, 2012
    / Reply

    very useful info to keep in mind

  3. / Reply

    Wouldn’t really worry about CSS selectors specifically, it more important to limit the amount of HTTP requests and image file sizes used. It has a far greater affect on site performance.

  4. / Reply

    Faraz, this was very helpful. While writing CSS have these in mind won’t take much time but result is effective

  5. / Reply

    Great stuff. Visual quality vs performance has been with us forever and always will be.

  6. / Reply

    I was looking for ways to speed up my website since it has heavy CSS. Thanks now i can speed it up a notch!

    • Dariusz Siedlecki,
    • May 6, 2012
    / Reply

    Once more, but without the tags:

    “Move link Elements from the Document Body to the Document Head”

    …better yet, just move them to the bottom of the BODY. Having them in the HEAD actually slows down the browser, since it has to download everything from the HEAD before it’ll start rendering the BODY.

    So move them to the bottom of the BODY element. That’s the best practice. If you have something which is 100% needed for the page, you can consider having it in the HEAD.

    • cythux,
    • May 6, 2012
    / Reply

    I work with classes like Bootstrap, and other CSS Framework!
    So i can it use multiple, and i use HTML5

    • fjpoblam,
    • May 7, 2012
    / Reply

    It is good, I think, that you added the note about “not being dogmatic”. Ethan Marcotte and others have suggested a fix for “mobile-first” designs whereby images are handled with a combination of viewport meta spec, flexible body, and images specified with “size:100%”—not necessarily fast, but effective. Also, though #IDs may seem to be effective, careful semantic structure in the HTML may both eliminate the need for many #IDs at all, and reduce the bandwidth required for sending the HTML; seems to me a toss-up between creation of superflous #IDs for speed in CSS rendering versus bandwidth in file transmission. Who wins: CSS+HTML bandwidth, or rendering speed?

  7. / Reply

    CSS is always helpful for designers as it gives the full access from a single place of the code and there are so many daily updates for the CSS and definitely it will work for the betterment of the CSS.

  8. / Reply

    It’s good to get a reminder of these things especially pseudo elements.

  9. / Reply

    NIce tips… thanx 2 share with us..

    • HTM,
    • May 10, 2012
    / Reply

    it is good to specify the width and height of the image. But how to be responsive to the design point where the height and width of a bad thing?

    • Mircea,
    • May 16, 2012
    / Reply

    @Dariusz Siedlecki:
    This guy is right.

    And instead of images, now we can use CSS3 and HTML5. Usualy, on a webpage we can do a css3 gradient instead of background images.

    • Alossia,
    • April 13, 2014
    / Reply

    Thanks for this useful post! I’ve bookmarked for future reference.

    • YemSalat,
    • November 14, 2014
    / Reply

    This post is a bad advice.
    Do you realize how quickly the modern browsers can render CSS?

    • ernest meyer,
    • February 20, 2016
    / Reply

    Well, I found it helpful. I optimized the rest of my site so the load time is 600ms, and now the 150ms to do all my css3 and universal selectors for my my incredibly small css file is significant. If it takes an extra 10ms to fetch the css file, and the render is 50% faster, my site is 10% faster. I just don’t know how to get that 50% faster bit. So thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *

Deals

Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.

d
c