Cascading Style Sheets or CSS files are an integral part of all modern websites. It allows you keep your content and layout separate and maintainable over the long run. This also mean that these files can grow in size over time and can negatively impact the page load time. When you optimize CSS files for size, you reduce the time it takes to download, parse and render the pages.
Even if the CSS files are not that large in size, it still helps to keep them as small as possible both for speed and maintainability. It is beneficial to load the CSS file as fast as possible, so as to allow the browser to render the content quickly and correctly. Moreover, it is quite likely that the same CSS file is used in most or many of your pages, which means optimizing a single CSS file can potentially speed all pages across the domain.
If you have a high traffic site, then every byte counts. There are several easy ways you can reduce the size and optimize CSS files.
Remove Unused Selectors and Rules
It is quite possible that there several rules left behind in the CSS file that are not used in any pages. This can happen especially if the website has gone through one or more iterations of layout changes. It is also possible when there have been active changes to the content.
It is not hard to identify these rules, if you are the person who have been actively working on it. But sometimes you might be working with legacy scripts which means you will need a easy way to identify unused rules. There are a couple of browser add-ons and extensions that allow you to track down these rules quite easily…
- Dust Me Selectors : A Mozilla Firefox add-on that allows you to see rules that have not been used in the current page. It also has the ability to spider a website, which is useful when working with multiple files.
- Chrome Dev Tools: A development that is built into and shipped with Google Chrome browser.
- CSS remove and combine: A chrome extension which works similar to Dust-me Selectors mentioned above.
Make sure that you run the tool on all your webpages and not just a few.
Remove Duplicate Selectors
This is a little more involved than identifying unused rules. This refers to those selectors that does exactly the same thing and apply the same rules but with different names. It is quite possible that both of these names are used in your webpages, which could potentially be replaced by one.
There are some utilities that allow you to find many of these duplicate rules. Before we delve into that, there are a couple of different tricks you can follow during development that will allow you to easily detect these rules at a later time…
Keep Rules Sorted: Always write the rules inside selectors sorted in alphabetical order. This allows you to search and find duplicate easily. You can also write a simple script (or a third party CSS beautifier) that will take a CSS and output a sorted list.
Name Classes Appropriately: There are no set rules on how you name the CSS classes. You should follow a pattern during development, that will give you a good idea as to where (which pages) exactly it is used. For example, prefix class names that are used across many pages with common. This can get quite wordy, but you can always search and replace these long names with something more appropriate after optimization (Also, check out the section below on length of class names).
A couple of utilities that will help you with identifying duplicate selectors…
- uCSS : This is a utility that attempts to find duplicate selectors. Your mileage will vary depending on the how your website is coded.
- CSS Lint: CSS Lint has ability to identify duplicates and warn you about them.
- CSSCSS: This is a command line utility which allows you to identify most redundant rules easily.
These tools can help you identify straight forward duplicate selectors, but not the ones that are “mostly” duplicates. See the section on merging selectors below to see how you might be able combine different selector rules to reduce the size.
Use CSS Short Hand Notations
Whenever possible use the CSS shorthand notations. Short hand notations are available for rules such as margin, padding, background, font etc.
As an example, use the following
margin: 10px 15px 0 20px;
Merge or Combine Selector Rules
This is often a tricky one. Identify selectors that apply mostly the same rules, but defer only in one or two of them. These can usually be merged into one single class, with the second rule overriding the rule or adding to them.
Here is a simple example of this….
The above two rules can be rewritten as
If you are using a CSS pre-proccesor like LESS or SASS, it makes it even easier to identify these rules or to avoid them.
Merge or Combine CSS files
This, of course holds true only if you use multiple CSS files in your website. After optimizing different CSS files, you could end up with several small optimized CSS files. Accessing and downloading each and every file separately will require the client to make several connections to the server. Considering that creating a connection to the server is that most resource intensive part (even with HTTP pipe-lining and all), it might be worthwhile to have just one file.
Of course, exactly how many different files you want to have will depend on how your website is structured and the actual file size of the CSS scripts.
Remove Unnecessary Characters
There are some characters that do not affect the parsing of the script. One of the most common character left behind is the semi-colon inside the selector. The last semi-colon inside a class or selector is not needed, I know it is only one character, but multiply it with the number of selectors you have
Another one is the size specification for zero. When you specify the width or size of elements or tags as zero, it is not necessary to specify any dimension such as “px”, “%” or “em”
padding: 10px 0
Many modern day CSS compressors allow you to do this dynamically.
Reduce the length of Selectors and Class names
The browser does not care much about the descriptive class names that you have in your CSS. As long as it is unique across the website, it will work just fine no matter how small and cryptic it is. Having a descriptive or human readable selector or class name has its advantages. It helps with the maintainability of the code and helps to keep them unique and not clash with other third party CSS names, if you happen to use other scripts or plugins.
This works along the line of obfuscation, apart from the fact that you are not trying to prevent code stealing per se. The only downside being that you will have to do this manually, as it needs that the usage of these class names needs to be changed as well. You can easily do it with the search all and replace functionality in any half way decent editor.
Minify CSS files
The next step is to take out all the characters in the file that are not needed for the rendering purposes. This includes comments and white space characters. Fortunately this is a very commonly used feature and there are several different utilities that perform this on the fly.
In addition to the tips described above, there are couple of other techniques that can be used to further speed up the delivery of style sheets. The following more specifically deals with how the CSS files are delivered and rendered at the client side but still falls under the realm of optimization. So, for the brevity purposes i will mention it here…
Inline CSS file dynamically
If your already minified and highly optimized CSS files is small, you can inline the optimized CSS file into the webpages. This reduces the need to create another HTTP connection to your web server and allows it to be downloaded along with the file content.
Many CDNs have the option to auto-magically embed the CSS file if it falls below a specified size threshold. This will also allow the content to be rendered in one pass. For example, in Google Page Speed Service (GPSS) you can enable the option to inline the CSS.
I usually recommend the CSS to be embedded if it below 4096 bytes.
Browsers match the elements in a pre-defined order, which means if your selector matches early in the process it gets rendered faster. There are mainly four different types of selectors: IDs, classes, tags and universal. Browsers mostly tend to match them in that particular order.
So when writing selectors, try to use ids as much as possible followed by classes and tags. Stay away from universal selectors as much as possible.
Word of Caution
Over optimizing the CSS code can actually make the code hard to read and maintain over the long run. If you are dynamically processing it and working off a human readable file then you should be fine. For this very reason, if you are not already using a CSS pre-processor such as LESS or SASS, I highly recommend that you do.