7 Tricks for Improving CSS Performance

By Cody Arsenault
Updated on April 12, 2024
7 Tricks for Improving CSS Performance

Cascading style sheets can turn boring HTML documents into dynamic webpages, but haphazard use of CSS can cripple a website before it even starts rendering. This guide will cover some quick and easy ways to fine tune your website's CSS performance so that you can deliver content more quickly to your users.

What is CSS?

Cascading style sheets, or CSS, is the language used to define a website's visual presentation based on the content provided in a markup language document. It is considered one of the "cornerstone technologies" of the web alongside HTML and JavaScript. CSS is typically stored in external style sheets, or .css files, but it can also be integrated directly into HTML documents.

CSS allows for a separation between a website's presentation and content, which makes websites more accessible to different devices. Keeping information about colors and fonts separate from content also reduces website complexity since several HTML pages may share the same CSS file. However, if used improperly, CSS can become a stumbling block for your website's performance from the outset.

CSS performance and website speed

When evaluating a website's speed, there are a variety of performance metrics to measure, however two that stand out are:

  • Time to first byte
  • Time to start render

The time to first byte refers to how long it takes for visitors to receive the first byte of data after requesting your URL. The time to start render is the point at which the user's browser actually begins displaying content. The former is largely dependant on your server setup, but the latter depends more on how your CSS is structured.

That said, browsers won't start rendering until they receive data, so a slow time to first byte will obviously push back your time to start render. Therefore, you should prioritize resolving any potential issues with your server before you can reap the full benefits of optimizing your CSS performance.

How CSS performance affects time to start render

Before a browser can start laying out a webpage's content, it needs instructions in the form of HTML and CSS. Thus, rendering cannot begin until all external style sheets have been downloaded and processed. The more round trips this requires, the longer visitors have to wait.

Using external CSS involves making one or more HTTP requests, so your goal should be to minimize the number of required requests as much as possible. For example, putting your plugin, banner, and layout link styles into a single .css file can significantly speed up your time to first render. We have a tutorial on other ways to limit HTTP requests in WordPress websites.

Improving your CSS performance: An introduction to inlining

One way to ensure speedy delivery of CSS is the practice of inlining. Inlining means inserting external CSS resources directly into HTML documents. This technique works best for smaller resources, but it nonetheless makes a noticeable difference.

Inlining CSS cuts down on the amount of data the browser needs to download before it can start rendering a page. When you use external CSS files, they must be downloaded separately after your markup document finishes downloading. Inlining lets you kill two birds with one stone, so to speak.

To inline CSS, simply copy the desired CSS code from your external CSS file, and paste it between style tags in the head section of your HTML document like so:

<head>
    <!-- Your header markup -->
    <style>
        .your-styles {
            font-weight: bold;
        }

        .etc-etc {
            color: #222222;
        }
    </style>
</head>

Inlining larger CSS resources

If you try to inline a large CSS file, you may get a warning from your performance testing tool indicating that your above-the-fold content is too large. Therefore, for larger CSS files, you should inline only the CSS required to render your above-the-fold content. Then you should load the full style sheet asynchronously so that the page can continue rendering while it's being parsed.

Critical CSS is a GitHub project to help you pick out which CSS belongs above the fold, but you should also do a manual check to make sure no critical components were left out.

After minification and Gzip compression, all of your above-the-fold styles, scripts, markup should ideally weigh less than 14 kb in total. Since 14 kb is roughly the amount of data a server can send in the first round trip. Staying under that threshold allows users to get everything above the fold in the first data packet they receive.

Improving CSS performance with async loading and caching

The aforementioned trick saves the user's browser one round trip to your server, so they'll see content more promptly upon their first visit. Unfortunately, this perk comes with a price: The user's browser doesn't cache the CSS, so everything must be loaded from scratch upon each future visit. If you have fairly simple CSS, this isn't such a problem; however, in most cases, you'll still want the users' browser to cache the majority of your CSS. That's why many web developers just inline the CSS on their homepage or landing pages while using external CSS for the rest of their site.

A clever way to get around this issue involves asynchronous loading. Unfortunately, there isn't a way to asynchronously load CSS files natively, but you can use a script like loadCSS.js to do the job.

Tools to improve CSS performance

If you want to see how other developers structure their CSS, Varvy's CSS delivery tool can give you an overview of how any website uses CSS. It's a great tool for evaluating your own projects and comparing them to others.

More tips for improving CSS performance

1. Use preload and HTTP/2 push

The preload resource hint tells browsers to fetch resources earlier than they would otherwise. To give your CSS a head start, set it as a link tag in your HTML document like this:

<link rel="preload" href="/css/styles.css" as="style">

Alternatively, you can include preload as an HTTP header in your server configuration:

Link: </css/styles.css>; rel=preload; as=style

If your server is configured for HTTP/2 (which it should be) preload will be interpreted as a server push. KeyCDN also supports server push which will help even further accelerate the delivery oh high-priority CSS files. To learn more, read our HTTP/2 server push announcement blog.

2. Don't inline everything

Don't bother inlining everything within your HTML file as this will cause the initial HTML doc to increase in size and thus take longer for the TTFB.

3. Concatenate and minify your CSS

Concatenating your style sheets into one file and sending out a minified version can drastically reduce the size of your CSS. Learn more about this process in our minify CSS, JS, and HTML article.

4. Reduce the size of your style sheets

The smaller your style sheets are, and the fewer selectors they contain, the less work browsers will have to perform when rendering your webpage. Therefore, you should do your best to remove unneeded selectors, leverage utility classes and avoid duplicate CSS code. You can use a tool such as uncss to make sure your style sheet contains only the requisite CSS code.

5. Be selective of your selectors

Speaking of selectors, using the descendant selector forces browsers to check all of your descendant elements for a match, so they can create more problems than they revolve. Universal selectors can also be rather costly, so steer clear of them too. Use shallow selectors when possible.

6. Avoid expensive properties

Certain CSS properties are significantly more expensive than other ones, so they should be used conservatively. These are a few properties to watch out for:

  • border-radius
  • box-shadow
  • filter
  • :nth-child
  • position: fixed;
  • transform

It's not a problem to use the above properties here and there, but if they appear hundreds of times per page, then your overall CSS performance may suffer.

7. Avoid @import

Never use the @import directive to include external style sheets because it blocks parallel downloads. This is an archaic practice. Instead, always use the link tag.

Summary

No matter how dazzling a webpage looks after it is finished loading, none of your efforts matter if visitors turn away before that point. Integrating the above strategies into your coding will allow you to build websites that render faster and perform more consistently, which will encourage new guests to keep coming back.

  • Share

Supercharge your content delivery 🚀

Try KeyCDN with a free 14 day trial, no credit card required.

Get started

Comments

Comment policy: Comments are welcomed and encouraged. However, all comments are manually moderated and those deemed to be spam or solely promotional in nature will be deleted.
  • **bold**
  • `code`
  • ```block```
KeyCDN uses cookies to make its website easier to use. Learn more