Optimize Your CSS for Faster Websites

Optimize Your CSS for Faster Websites


May 16, 2022
by jessicadunbar

CSS is the displayed content that makes your experience on the web as enticing as it is: layouts, colors, responsive designs, fonts, UI elements, and more. It provides intuitive visual cues that communicate status like task completion, network outage, or game characters disappearing into smoke after dying. But it can all be pretty heavy – and generally speaking, the less code goes through a web page, the less friction it will contain. Heavy and complex code can lead to poor performance and low maintainability.

Alarmed by the issues caused by poorly optimized CSS, developers have been focusing on reducing CSS JavaScript payload sizes. Indeed, they have found out that CSS can slow you down in a multitude of ways. Such as by rendering blocks or stopping the parsing of HTML.

As well as facing these challenges, the primary goal of making your CSS more efficient is creating faster websites that enhance customer engagement, retention and rank higher in Search Engines.

Slow-loading websites are often due to bloated code; reducing your CSS stylesheet's file size by even a few kilobytes can usually help usability. To help with the task, we have compiled fifteen ways to go about CSS optimization:

1. Image Sprites

This age-old technique allows you to package your images into one large .png file, an ideal choice if your website uses a lot of graphics since it will reduce HTTP requests and improve your page load time.

2. Minifying CSS

Minification is about cutting out unnecessary portions of code to reduce its file size. Code is usually made for human consumption, allowing them to review, maintain, test and deploy it. Minifying CSS means removing comments, spacing, indentations, naming conventions, and other elements used to boost the code's productivity and maintainability. The browser does not need this white space to execute the CSS code.

Minifying CSS is compressing the file into a newer one with minimal white space (you can do this using automatic compressors available online), sending only what the browser needs to execute the code on the target device. This will speed up download and execution time on the browser, even if the file has only been superficially modified.

Note that code minification and compression are two different techniques, which can even be used together to deliver optimized code. While minification alters the content of code by stripping out unwanted characters and formatting, compression reduces file size by compacting the overall file before shipping it to the browser.

3. Reducing Unnecessary Code

In the same vein, reducing unnecessary and redundant CSS code, which easily slips into the code as feature count increases, is an excellent trick to improve page load. While it may be a scary task, here are a few recommendations:

  • Organize your file into clearly marked, smaller ones (partials). This will help you identify what to remove when the time comes.
  • Naming methodologies can help with the development of discrete components.
  • Avoid deeply nested Sass/preprocessor declarations, which can enlarge the expanded code drastically.
  • Steer clear of using !important to override the cascade.

4. Separating CSS from JS

It's also helpful to remember to put your CSS stylesheet at the top (between

tags), while your JavaScript sits at the bottom because of its increased size and the effect it can have on website speed. This can be prevented by ensuring that your CSS code is loaded before the rest of the page.

5. Splitting CSS Files

If you're targeting multiple browsers (Chrome, Firefox, etc.), you can also split CSS files (perhaps in various stylesheets). For example, you could use Firefox conditional statements to load a different stylesheet instead of directly trying out CSS hacks in a single stylesheet. This would mean that you don't have to load up Firefox code while using Chrome, which would reduce the CSS file size by a great margin.

6. Reduce Whitespace

This is an easy one, which you should always keep in mind that white space can take up lots of bytes and make a big difference on larger scale projects.

7. Documenting your Code

It's also good to always keep in mind to document your code wherever possible. For example, you can do this by using CSS comments like /* Comment here */ will lead you to quickly identify useless code down the line. The additional space taken by comments is easily negligible overall anyway.

8. Organizing your Code

This is a less known technique that can drastically reduce your CSS file size and, once again, boost your website speed. One of the main problems in modern web designs is duplicates and redundant code. This can be easily avoided by putting your VSS classes into the right set of branches. Therefore, organizing what once was a messy CSS code into hierarchical branches won't take you very long but could definitely improve your website as a result.

9. Avoid Base64 Bitmap Images

It is common knowledge that standard bitmap JPGs, PNGs, and GIFs can be encoded to a base64 string within a data URL. But there are drawbacks to this technique, which means you might want to steer clear of it entirely. Firstly, unbeknownst to most developers, base64 encoding is typically 30% larger than its binary equivalent. Moreover, the receiving browser must parse the string before it can be used, and on top of this, altering an image will invalidate the whole (cached) CSS file.

While the benefit is that fewer HTTP requests are made. But this rarely provides a noticeable benefit — especially over HTTP/2 connections. In general, it can be a good rule of thumb to avoid inlining bitmaps (unless maybe if the image is unlikely to change often – meaning the resulting base64 string is unlikely to reach a high number of characters).

Replacing Images with CSS Effects

Many visual effects such as shadows, borders, gradients, and rounded edges don't actually need background images to be successfully deployed. Instead, you might want to define an "image" using CSS code, which will demand considerably less bandwidth and will also serve you down the line by making it easier to modify and animate.

11. Removing Unnecessary Fonts

Services such as Google Fonts make it easy to add custom fonts to any page, and it's just as easy to get carried away with them. However, there can be hundreds of kilobytes of font data in a single line of code. Keep this in mind, and make sure to only load and use the fonts you need. The same goes for weights and styles no need to load up all of them, only the one that will be deployed on your website (such as roman, 300 weight, bold, no italics).

Wherever possible, you should also limit the character sets. You can pick certain characters on Google fonts by adding a &text=value to the font URL. For example, type fonts.googleapis.com/css?family=Open+Sans&text=SitePon for displaying "SitePoint" in Open Sans.

You can also use variable fonts, which make files smaller by defining multiple weights and styles by interpolation. Unfortunately, this is currently limited to Chrome, Edge, and some editions of Safari, but it's safe to assume it could grow rapidly.

You should also consider OS fonts since they are now considerably less common than they once were and could make a big, while hardly noticeable, difference.

Using Modern Layout Techniques 

If you keep up to date with modern layout techniques, you'll know that using CSS float to layout pages is actually a hack that requires lots of code and tweaking to work, and even then, floats can break if media queries aren't added for smaller screen sizes. Consider the more straightforward and lighter alternatives:

  • CSS Flexbox for one-dimensional layouts – they can wrap to the next row according to each block's widths. It is ideal for menus, cards, galleries, etc.
  • CSS Grid for two-dimensional layouts. This is ideal for page layouts and will provide you with explicit rows and columns.

13. Cling to the Cascade!

While CSS-in-JS has provided developers with a lot of benefits, and you should feel free to carry on using it, it's worth exploring what the CSS cascade can do for you, rather than spending energy relentlessly working against it. You can set default fonts, sizes, tables, colors, and form fields that will be applied to every element in a single place and will rarely ask you to declare every style in every component.

14. Simplifying Selectors

This is a simple but efficient piece of advice. While even the most complex CSS selectors take milliseconds to parse, reducing complexity will still reduce file sizes if your goal is to aid browser parsing, which is worth keeping in mind.

15. Really Understanding CSS

The most important tip is to make sure you fully understand your stylesheets and are able to navigate them as efficiently as possible. While CSS is easy to learn, it can be challenging to master entirely. But you will need to if you want to create efficient client-side code. It will revolutionize your workflow, improve your website performance and enhance whatever you set your mind to producing.

Page Updated 7/16/24, 3:12 PM