GitHub Download

How to optimize CSS code for a faster website

CSS provides the "tools" we need to make visually-striking websites, and we'll often find ourselves exploring new methods, functions and features that will help us raise the aesthetic impact of our site.

But it's important to remember that the CSS code that makes our websites look great also has a significant impact on page-load speed, not just in terms of the number and size of files that need to be downloaded by the user, but also how efficiently it can be rendered by the browser.

In this article, we'll give you some useful tips for creating optimized and efficient CSS code that'll help your site get improved results in tests such as Page Speed Insights, and in turn provide a smoother, user-friendly site experience.

Keep the number of CSS files under the limit

Of course, from a technical point of view there isn't a hard limit on the number of CSS files that could be loaded. However, in practice, having a large number of files can have a negative impact on page-loading speed; this is especially true if some of the files are loaded from external domains. So, it's definitely worth your while to audit your load process to see just how many CSS files are required during the website load and consider whether this number can be reduced in any way e.g. by combining files into a singular larger file.

In addition, files that are loaded from different domains should be avoided; the perception of your website can be damaged if these other domains encounter connection issues or downtime. Instead, if the files are required and can't be cut out entirely, consider incorporating them into local files (which can then be included in the collective CSS file) so that they are loaded alongside the regular files without any need for external connections.

Attention! When it comes to reducing the amount of CSS files, remember that fewer doesn't necessarily mean faster. In sites that have a huge number of CSS files, combining them all into one gargantuan 1MB file may have more of a negative impact than having lots of small files. In such instances, try to be methodical and logical in your approach to combining files; combining files that offer similar functions or applications within your site can be a easy way to reduce sizes without mashing everything together. For regularly-sized sites though, combining all the CSS files into one is a sound solution.

Reduce repetition and redundancy in your CSS code

In many instances, redundancy is useful; it prevents a single error botching the whole operation. But in CSS code, redundancy can simply lead to more code being loaded than needed. So what options do we have to avoid this issue?

In an ideal world, each subpage would only load the CSS code it needed to render the specific HTML used on that subpage, ignoring everything else. However, in practice this is often impossible to achieve. This doesn't mean that there's nothing that can be done; instead, consider which page elements have specific uses for specific subpages or subpage types. For example; if you have an online store, it doesn't make sense to load the CSS code for rendering the store elements on every subpage, as things like checkout pages simply won't need it. By identifying such elements, we can then extract the code for the element (the store's CSS code, in this example) from the main CSS file, and load it only on selected subpages as a separate file.

With this method, we can reduce the size of the CSS code that is used on individual subpages without going too crazy with dividing the code into an increasing number of smaller files.

The size of your CSS code matters

The longer the straw, the longer it takes to suck the water up it (and thus, the longer it takes to get a drink). The more CSS code, the longer the browser takes to retrieve and parse it. And if you want your users to feel refreshed with fast load times, then you'll need to minimise the amount of CSS code sent to the browser. There are multiple steps you can take to bring down the total file size, and remember that even a small reduction can have an impact on load times.

Enable GZIP compression on your server

CSS files are really just text files, so we can enable GZIP compression in the server configuration to significantly reduce the amount of data sent. In the right conditions, this simple action could reduce the size of the data transfer several times over.

If you're not sure if your website uses GZIP compression, you can check it using this tool: https://www.giftofspeed.com/gzip-test/

The method for enabling GZIP compression differs depending on the server software used, so your first stop should be checking the configuration page of your hosting account or the hosting account's management control panel, which is most likely to include the options for enabling or disabling GZIP compression.

Compress your CSS code

The files can be compressed with GZIP, but the CSS code itself can also be minified, which will further reduce the size of the resulting file. Thanks to this, the code will have its unnecessary whitespace removed and some entries will be additionally simplified.

If needed, you can compress your CSS files with online tools such as CSS Minifier (https://cssminifier.com/), but in practice it's much better to implement CSS compression into your automated process for building your final CSS code e.g. from SCSS files; this way your code will always be as efficient as possible and you reduce the chances of a file slipping through the net undetected.

Simplify the Selectors

When we are writing CSS code, we're often looking for the code to function as intended first, with efficiency being comparatively less-important. Due to this, it's easy to end up creating selectors that are unnecessarily complicated. Therefore, it is worth analysing whether a given selector can be shortened while still providing the same effect.

For example - if you have the following code:

.resources-list .resources-list-item .resources-list-item-link {}

we can probably just write:

.resources-list-item-link {}

because this is quite a complicated and unique class name which isn't likely to appear elsewhere on our site.

The benefit of this kind of small change is twofold; we make the file size slightly smaller by reducing the amount of CSS code, but the simplifying of the code also provides some relief to the browser engine, which now doesn't need to analyse a complex selector which wasn't optimal, as it requests multiple lookups through multiple nesting levels i.e. first it looked at the browser element .resources-listand then searched at any nesting level in this element for the .resources-list-item, and when found, it searched yet again at any nesting level in the .resources-list-item for an item with the class .resources-list-item-link. If it was the only one in the code the impact might be unnoticeable, but if this particular faux pas is prevalent in our code we would definitely feel the effects.

Certainly, CSS preprocessors that include a function for nesting CSS rules (nested rules) contribute heavily to the creation of redundant selectors. This code is very comfortable and easy to write, but as a side-effect it can generate a lot of redundant object code that we should be wary of.

Get rid of old and redundant vendor prefixes

Technology marches on, and many prefixes that were essential for earlier browser versions become redundant and unused. Firefox 5-15, as an example, required the -moz -transition prefix, while later versions did not. Since Firefox 15 is pushing 9 years old at this point there's really no need to include this prefix, which in turn reduces your CSS file size.

To help you identify which vendor prefixes are no longer necessary you can take advantage of online resources such as CanIUse, where you can specify the browsers you wish to support and see which prefixes they require. Alternatively, you can automatically update the prefixes in your CSS file using Autoprefixer, which uses the CanIUse database to check which prefixes are required or not.

Watch out for the @extend command when using SCSS

If you are using SCSS you are surely familiar with the @extend command, which makes it much easier to style items with existing selectors. Unfortunately, in some cases this functionality can add up to several hundred kilobytes (!) of redundant code - especially when used with selectors that contain a lot of nested elements. When using this command we should be constantly analysing whether the resulting CSS code is not growing suspiciously quickly.

It is also worth considering using @mixin instead of @extend - especially in combination with GZIP compression, you may find that you get better results, even with the seemingly more code, because GZIP compression prefers repetitive fragments of compressed content. You can learn more about this at the following link: https://csswizardry.com/2016/02/mixins-better-for-performance/

CSS and page rendering speed

One of the simplest solutions to speed up the page is to load the whole CSS code in the <head> section of the site. However, this won't be the optimal solution if the CSS code is too heavy; overloading the section with too much CSS code can cause significant delays to the load time of the HTML file, which ultimately is the content the user wants to see.

A much better solution is to use the so-called critical CSS method i.e. extracting the CSS code fragments that are responsible for rendering the top part of the page to be loaded initially, allowing the user to begin reading content faster, and then reading the remaining CSS code in an asynchronous manner.

With this method we don't have to increase the size of the document by any meaningful level, and at the same time we avoid running into a resource-loading issue that will interrupt page rendering.

To generate Critical CSS, you can use dedicated services such as https://criticalcss.com/ use ready-made NPM modules such as https://github.com/addyosmani/critical or https://github.com/filamentgroup/criticalCSS or simply use the Coverage tab in Chrome Dev Tools: https://developer.chrome.com/docs/devtools/coverage/

CSS and interface performance

When it comes to overly-long selectors, it takes quite a bit of effort to overuse them to the point that they will have a major affect on the rendering speed of your website. This is certainly not true, however, if you use inappropriate CSS properties, which can severely degrade page performance.

Perhaps the most well-known example of this principle in action is the margin-left property being used in the animation slider instead of the transform property. But why would this create a performance difference? It all stems from the way the page is rendered by the browser engine.

The margin-left property requires calculations to be run for all three stages of rendering the page: the layout stage, the paint stage, and the composition stage. For the transform property, calculations in Chrome and Firefox are performed only in the composition stage. In some cases, the difference in fluidity can be really large.

So if making your website as efficient as possible is a priority to you, take some time to learn how individual CSS properties can affect the page-rendering process via the CSS Triggers website (https://csstriggers.com/).

CSS as a way to limit the number of queries to the server

CSS code allows you to embed graphics and even fonts as values through the use of Data URI. This in turn means that we can avoid loading many small files for one CSS file. However, we should remember that, due to the base64 format used, the embedded files are slightly larger than the originals. The use of such an approach makes sense mainly when we want to avoid loading small files.

More on Data URI read here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs

In Summary

Taking into account all we've covered today, we can see that CSS code affects, in the context of site performance, the following:

  • the number of queries to the server (and sometimes help it to be optimal)
  • The website load time (the faster we load the necessary code, the faster the website content will appear)
  • browser performance (poorly written selectors, poorly selected properties or a huge amount of CSS code can slow down the browser engine)

By taking these things into account when writing our code, we can develop the experience necessary to make building fast and efficient CSS code for our sites a habit, rather than a chore.

Subscribe

Get the latest Publii news, updates and more delivered directly to your email inbox

You can change your mind at any time by clicking the unsubscribe link in the footer of any email you receive from us, or by contacting us at contact@tidycustoms.net. By clicking below, you agree that we may process your information in accordance with our Privacy Policy.