How to Optimize CSS Delivery for Site Speed

Thanks to CSS, our web pages no longer need to look like they did in the 1990s. It’s an incredibly powerful tool that allows us immense customization, and even the ability to create complex designs.

Even though the introduction of CSS was a major upgrade and has had almost no downsides it is important to take into consideration the effect the use of CSS scripts can have on page speed, especially when it comes to the rendering of a web page.

Poorly delivered CSS makes the browser wait to download and process the styling data before it fully finishes rendering to display your webpage. So it’s very important to optimize CSS delivery and avoid additional waiting time while loading CSS assets that can slow down a web page.

When a user requests a website, the browser must process all the information available to determine the layout and style. The problem is that until this is completed, the user sees a blank white screen or a broken page layout.

If the browser can make 1 round trip to get your style information, the user will only see that white screen for a fraction of a second. Your visitors are likely going to be staring at the white screen for a while. At least until they get frustrated and leave!

Each of the stylesheets needs a request to be made by the browser to be downloaded from your server. A request is like a roundtrip that the browser has to make before it renders the website. Obviously, the number of roundtrips needed will have a large impact on how quickly your site loads.

Let’s find out how to analyze CSS issues on your site and optimize the assets.

Perform an Audit of Your Site

First things first, you need to test your website. Most performance audit tools will give you some indication of the CSS problems you have. PageSpeed Insights and WebPageTest are ideal testing tools but you have can use GTmetrix, SpeedVitals, or Pingdom to analyze your site.

render-blocking-issues

Although some of the issues might not be related to CSS, you will be able to identify the ones creating major bloating and slowing down the page. For example, you may get an excessive number of stylesheets that are blocking the first paint of your page thus marked as ‘Render Blocking Resources.

You may also check in the waterfall section to get an idea of how the CSS files are getting loaded. Once you know how the styling files are loading you will be able to apply optimization strategies to reduce page load time significantly.

optimize-css-delivery

How to Optimize CSS Delivery On Your Website

CSS optimization starts with resource optimization that is a key part of a web page optimization process. Let’s see these simple tips that could improve/optimize CSS delivery.

1. Avoid use of @import directive

CSS @import rule allows you to import an external CSS file in a CSS script. Although it hampers page speed because the @import function calls every imported file individually instead of loading them synchronously with other files needed to render a particular page.

This whole process creates additional HTTP requests too. In general, the more HTTP requests your web page makes the worse it is for page speed. 

Downloading the CSS files in parallel is the key to loading a page faster. So you would want to use a <link> tag or concatenation instead of @import.

<!-- Using @import -->
<style>
@import url('demo.css');
</style>

<!-- Using <link> -->
<link rel="stylesheet" href="demo.css">

2. Avoid CSS Expressions

CSS expressions are used in javascript to set up CSS values. Since they’re possibly executed many many times they downgrade a webpage’s performance. CSS expressions are no longer supported by modern browsers. Instead of CSS expressions, you can use the calc() CSS function.

/* CSS expression */
width: expression(document.body.clientWidth - 50);

/* CSS calc() */
width: calc(100% - 50px);

3. Compress CSS with GZIP or Brotli

Both Gzip and Brotli are techniques to compress your website’s files usually CSS, Javascript, text files, etc. Brotli and Gzip are similar in that they compress website files to make them smaller for faster loading.

These compression techniques can compress web files (mainly HTML, CSS, and JavaScript files) to a tinier version, sometimes up to 70%-80% smaller. This much smaller compressed version of a file is then sent to the browser of the user requesting it instead of the larger original file. The browser of the user will then automatically decompress the compressed file and serve the uncompressed original file. Since the files are much smaller the downloading process takes a lot lesser time.

You can check whether your web page is using Gzip/Broti compressions using this Gzip test tool.

Gzip Compression Test

In case you don’t have Gzip/Brotli enabled you can activate it in many ways.

One way to add Gzip compression to your WordPress site is by modifying the .htaccess file. Then copy and paste the code below between your beginning and ending WordPress tag.

# Compress HTML, CSS, JavaScript, Text, XML and fonts
 AddOutputFilterByType DEFLATE application/javascript
 AddOutputFilterByType DEFLATE application/rss+xml
 AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
 AddOutputFilterByType DEFLATE application/x-font
 AddOutputFilterByType DEFLATE application/x-font-opentype
 AddOutputFilterByType DEFLATE application/x-font-otf
 AddOutputFilterByType DEFLATE application/x-font-truetype
 AddOutputFilterByType DEFLATE application/x-font-ttf
 AddOutputFilterByType DEFLATE application/x-javascript
 AddOutputFilterByType DEFLATE application/xhtml+xml
 AddOutputFilterByType DEFLATE application/xml
 AddOutputFilterByType DEFLATE font/opentype
 AddOutputFilterByType DEFLATE font/otf
 AddOutputFilterByType DEFLATE font/ttf
 AddOutputFilterByType DEFLATE image/svg+xml
 AddOutputFilterByType DEFLATE image/x-icon
 AddOutputFilterByType DEFLATE text/css
 AddOutputFilterByType DEFLATE text/html
 AddOutputFilterByType DEFLATE text/javascript
 AddOutputFilterByType DEFLATE text/plain
 AddOutputFilterByType DEFLATE text/xml
 
 # Remove browser bugs (only needed for really old browsers)
 BrowserMatch ^Mozilla/4 gzip-only-text/html
 BrowserMatch ^Mozilla/4\.0[678] no-gzip
 BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
 Header append Vary User-Agent

Or if your site is connected with Cloudflare you can activate the Brotli compression with these steps:

  1. Log in to your Cloudflare account.
  2. Choose the appropriate domain.
  3. Click the Speed app.
  4. Click the Optimization tab.
  5. Toggle the Brotli switch to On.
brotli-compression-cloudflare

4. Minify CSS files

CSS modification means the removal of comments, whitespace, and newlines to significantly reduce the CSS file size which speeds up its downloading. The reduction of every single KB from your CSS files will positively impact your page loading speed.

If the original CSS is:

/* Clearfix */
.clearfix:after {
    clear: both;
    content: '';
    display: table;
    zoom: 1;
}

Then the minified CSS code would look like this:

.clearfix:after{clear:both;content:'';display:table;zoom:1}

To compress your CSS files you can use the online CSS compressor. The WordPress users can activate the CSS minify option in caching plugin.

compress-css-files

5. Combine Your CSS Files

As we know the browser has to work through the file requests to collect all the styling information needed to properly display our website. If the styling files aren’t being downloaded asynchronously, that’s a problem either. Hence the lower amount of files you are serving, resulting in a lower number of HTTP requests the faster the page will render.

If you’re building your website from scratch, this process is easy. Simply take the code from your various CSS files and paste them into 1 file. Done!

Just make sure you’re not using @import to pull the files in. This method doesn’t support simultaneous download, meaning it still needs to do one import at a time.

If you’re using WordPress or any other content management system, many caching plugins will also combine your CSS files with the click of a button. Just remember that each additional plugin you use can introduce more files that need to be downloaded, so keep those to a minimum.

combine CSS files
A note on HTTP/2 and combining CSS files

While combining your CSS (and JS) files is beneficial under HTTP/1, there is some debate as to whether it should be done with HTTP/2. This new protocol can handle parallelized downloads, meaning it may actually be harmful to force it to download 1 large file, rather than many smaller files simultaneously.

Most performance audit services don’t check for HTTP/2 and will throw a warning, suggesting you merge all files. This is another reason why page speed scores can be misleading. Make sure you test for yourself and see which configuration actually makes your site faster. You can check for HTTP/2 support here.

6. Avoid Inline Styling

Inline CSS can increase the HTML document size, leading to slower page load. Additionally, inline CSS is not cached, so every time you visit a webpage inline styles need to be loaded with HTML. Therefore you would always want to avoid inline CSS. Apart from that, there are downsides of inline styling such as lack of reusability, Lack of reusability, Maintenance problem, etc.

<!-- HTML & inline CSS -->
<div style="background-color: red; float: left; width: 50%;"></div>

rather use this –

/* CSS */
.item {
    background-color: red;
    float: left;
    width: 50%;
}
<!-- HTML -->
<div class="item"></div>

7. Keep CSS Selector Short

With bigger HTML files, and your CSS styles starts to become longer and longer, it might be worth looking into shorten and simplify them a bit by grouping CSS selectors and nesting CSS selectors. Additionally you would want to maintain the depth level of nested CSS selectors.

Reducing the depth level of nested CSS selectors is a key part of the effort to write efficient CSS selectors.

header ul.menu > li.active > ul.sub-menu {
    display: block;
}

/* the same, but more efficient */
.active .sub-menu {
    display: block;
}

8. Try your CSS on a CDN

CSS files are just another piece of static content that may be best served on a CDN. Not only are CDN’s streamlined for files like this, it can also reduce the load on your server. And if your audience has a large geographic distribution, you’re going to be serving it from a location closer to them. Learn more about the other benefits of a CDN for speed.

Most of the caching plugin in WordPress allow you to serve CSS files from CDN. You can configure them with a couple of clicks.

CSS-CDN-delivery
CSS file delivery settings with a CDN

9. Reduce Your CSS

Whether you decided to go with one CSS or several smaller ones, removing unnecessary CSS is always a good idea. Lots of CSS frameworks (like Bootstrap) include a ton of features (which makes them heavy!), but if you’re only using a little bit there’s no use supplying all the extra. Sometimes the framework will come with a custom downloader where you can select the features you’re using and it will provide you with a file of just your essentials.

Another reduction would be to remove the white space and various comments via minification that we have discussed earlier. While whitespace makes it easier for humans to read, the browser doesn’t need it. This minification makes our CSS files as small as possible, which reduces the overall size of our website.

There are many online tools that will take care of this for you. A quick Google search will reveal many options, but we recommend CSSminifier.com. Again, if you’re using WordPress, plugins like WPRocket and Autoptomize will handle this for you.

remove-unused-css

10. Prioritize Above-the-fold CSS

To really go above and beyond, we want to load our CSS for all of the styling that will be necessary immediately (think navigation menu, call to action, hero image, etc.). This allows us to defer CSS files for things like the footer and other sections that are down the page (anything the viewer would have to scroll down to see). These aren’t needed immediately, so we can load them after the DOM elements are presented.

Tools like this Critical Path CSS generator will analyze your site and create separate files for you. You can do this manually as you build your site. WP rocket and Autoptimize plugin has a module that can automate critical CSS delivery job for your site.

critical-css-settings-wprocket

Inline Critical and Small CSS Files

Once you have your separate files, you can inline the critical, above-the-fold CSS, and defer-load any other large CSS files.

You’ll also want to inline any small CSS files as well. Even though they may not be essential to the page, there isn’t any real benefit to loading files deferred unless they’re larger.

All of this amounts to a much faster-perceived load time because the non-essential CSS files are able to be loaded while the visitor looks at the upper-most content.

11. Cache CSS Files

Finally setting cache rules on CSS files to store CSS files in the browser cache reduces the load on your web server. This results in fewer HTTP requests which reducing a page load time.

You can achive this with modificatiion of .htaccess file or with a caching plugin on WordPress sites.

Either add this into your .htaccess file:

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType text/css "access plus 1 year"
</IfModule>

Or configure your caching plugin to serve cached CSS files.

Now Our CSS is Made for Speed!

You should feel incredibly accomplished after taking these steps to make your stylesheets load as fast as they can.

Even if you don’t feel comfortable with some of the options, taking even a few of these steps will ensure that your users get the best of both worlds – amazing styling and a blazing fast experience.

The most important thing to keep in mind is that you’re shooting for a site that is as fast as possible. Often times the various web performance audit services will fire off warnings that may not apply to you if you’re utilizing HTTP/2. Don’t worry about the number/letter score you see and instead focus on improving the various page speed metrics.

Let us know below how your CSS optimization journey went!

Additional Contents:

5 Best WordPress Speed Optimization Services You Can Hire

Is Google Fonts Slowing Your Site? Make Google Fonts Faster

The 5 Most Underrated WebPageTest Features

Leave a Comment

speedy.site

Feel free to reach us for any kind of queries regarding speedy site service and other related business.

HEADQUARTERS​, CANADA

220b 1 first street Collingwood Ontario Canada (Monday – Friday, 9:30 am – 5:30 pm)

ABOUT US

We are a dedicated team of WordPress developers and enthusiasts obsessed with site performance willing to help increase your site speed and pass core web vitals.