Minify your CSS files, speed and other SEO wizardry

June 30, 2010 at 4:32 pm 1 comment

Ouch! It’s been quite a long time since my last post due to the birth of my baby girl on April the 30th. It has kept me quite occupied lately. Now that she begins to sleep at night let’s go back to some web development thoughts sharing :-).

Creating a web site is actually very easy. There are a lot of automated tools and free blogs out there to help you do the job in no time. However if you want to go serious about it this is a whole other story. Here comes the questions about good practices, W3C standards, Search Engine Optimization (SEO), efficiency and speed among other subjects.

Today I’m going to focus on speed and more specifically on how you can reduce the size of you CSS files. This process is often called minification and even though it applies both to CSS and javascript, I’ll only focus on how to minify CSS files for now.

So what about speed?

As you may know Google has announced on April the 9th this year that web site rendering speed is now taken into account in their ranking algorithm. You can find the official announcement on their Webmaster Central Blog here as well as some comments from Matt Cutts here.

If speed doesn’t seem to be that much important (yet) for ranking it brings another obvious added value: the faster your website, the more responsive the UI, the better the user experience. In other words if people don’t have to wait for your web site to be rendered, they’ll be more likely to come back visit your pages.

More generally if you think for the future, you must have noticed that more and more applications are moving to the cloud while providing more features and a richer visual environment. Simply put in a few years we’ll probably have desktop like applications available online. Browsers become platforms that execute remote applications (mainly written in HTML, CSS, javascript and other web technologies such as PHP, Perl, ASP, servlets, …).  At one point in time the wide adoption of these remote apps will be about feature richness and speed compared to desktop apps.

How to minify CSS files?

Just as a reminder CSS stands for Cascading Style Sheets. While HTML describes the structure of a document (in terms of titles, paragraphs, sections, headers, footers, …) and holds its content (the text itself), CSS is used for rendering purposes (determining text fonts and sizes, colors, positioning, …). A CSS file is basically a text file that contains design and rendering rules for the browser to display your content.

One obvious way to compact CSS (as well as any other text content) would be to activate gzip compression on the web server (assuming you own your domain and have access to the web server configuration). This is of course a very common and recommended practice. Gzip compression can be simply set on Apache 2.2 with a directive such as the one shown below:

AddOutputFilterByType DEFLATE text/html text/css

For more information on Apache deflate module please refer to the web server online documentation.

However it is also possible to compact the CSS files themselves reducing their size by 20 to 40% even before the compression happens. While this is a good practice in a production environment, keeping minified versions of CSS for development and maintenance is a very bad practice, and you’ll understand why below.

Here is what a well written CSS file should look like:

body {
   margin: 0px;
   padding: 40px;
   color: white;
   background: rgb(119,119,119) url(../img/myBg.jpg) fixed;
   font: 1em Arial, sans-serif;

div > p {
   font-size: 0.8em;
   text-align: justify;

.clearFix:after {
   visibility: hidden;
   display: block;
   clear: both;
   height: 0px;
   font-size: 0em;
   content: " ";

and then once minified:

url(../img/myBg.jpg) fixed;font:1em Arial,sans-serif}
height:0;font-size:0;content:" "}

Pretty much unreadable don’t you think? And I’ve inserted newlines to actually improve readability :-). Now you certainly understand why you should have 2 versions of your CSS:

  • the normal non-minified “long” version for development and maintenance and
  • the minified version for your production (live) environment.

In the end even with such a simple example we’ve reached more than 28% file size reduction.

Now let’s have a look at the rules that I’ve applied to minify the CSS:

  • rgb colors should be replaced with their hexadecimal counterparts. In our case the body background default color rgb(119,119,119) becomes #777777 (119 decimal equals 77 hexadecimal) which can then be compacted even further to #777 following the rule that #RRGGBB can be shorten to #RGB. This is however  questionable with “standard colors”. Typically a color set to red (3 letters) is always shorter than #F00 (4 letters). Personally I tend to let the text written color values “as is” but I could certainly save some more bytes around.
  • A value of 0 doesn’t need any unit! Whether we’re talking em, px or % a value of 0 … values 0.
  • Lower than 1 decimal values do not need a preceding 0. Looking at the paragraph rule div > p the font size is set to 0.8em which shortens to .8em. In this case we still need the unit but the preceding 0 is unnecessary.
  • Multiple adjacent white spaces (including tabs) can be reduced to only one space and almost all spaces can be removed. Take care though spaces around shorthand property values and some CSS selectors are needed. Let’s take the example of the body background property again. It is followed by 3 space separated values: a color rgb(119,119,119) or #777, an image url url(../img/myBg.jpg) and a background attachment fixed. background is actually a shorthand property and replaces several individual properties among which: background-color, background-image and background-attachment. Instead of 3 separate properties we use only the shorthand version which is followed by several space separated values, corresponding to the values for each individual properties it replaces. Note that using shorthand properties is also an efficient way to compact your CSS and it’s usually considered a good practice that doesn’t impact readability.
    Another exception to take care about, some CSS selectors require as well to be space separated. In our example we use the div > p selector which can be minified to div>p without any issue. The elements being separated by the > sign each one (the div and the p) is clearly identifiable. However div p is another valid CSS selector and in this case the div and the p elements must be space separated. Without it (divp) the browser can’t tell which elements are concerned by the rule because divp isn’t a valid HTML element.
  • A corollary rule to the white spaces one: newlines aren’t needed. Once minified your CSS file should be one long long long line of text.
  • Finally you may have noticed that each rule is semi-column (;) separated. Minification allows for one exception, the last rule in a selector doesn’t need the ; before the closing curly brace }.

If you apply all these rules you should see a significant improvement in your CSS file size. Usually it ranges from 20 up to 40% reduction. Now in terms of productization process, it is recommended that you keep the non minified CSS file for development and that you create the minified version on the fly for your live environment (i.e. before transferring your CSS to the web server).

Write efficient CSS

Minification isn’t the only way to compact your CSS files. Writing efficient CSS is certainly as much important as minification. But what exactly do I call efficient CSS? One example could be to wisely use shorthand properties instead of their separate counterparts as shown below:

margin-top: 10px;
margin-right: 20px;
margin-bottom; 30px;
margin-left: 20px;

can elegantly be shortened to:

margin: 10px 20px 30px;

Another piece of advice could be “don’t think too linear” when writing your CSS. It’s very straightforward to crawl an HTML file and create the corresponding CSS rules on the fly as the elements appear in the HTML. However by doing that you usually need to duplicate entire portions of CSS. Hence it’s a good practice to come back to your CSS after a while and try to create generic classes or reorganize your rules keeping in mind that the last written rule always has precedence over any previous equivalent ones.

div {
    font-size: 1em;
    text-align: justify;
    color: white;

... and several lines down your CSS ...

p {
    font-size: 1em;
    text-align: justify;
    color: blue;

can be rewriten:

div, p {
    font-size: 1em;
    text-align: justify;
    color: white;

p {
    color: blue;

Again use this kind of optimization wisely. Keep in mind the readability and maintainability of your CSS rules. Sometimes it’s better to duplicate code than to optimize at best and get something in return you won’t understand a few months later.

CSS minifier tool

GNU General Public License v3 logoObviously you can’t minify a CSS file by hand. It would be a crazy job. So I’ve developed custom tools in PHP and Perl that do the trick for me. You can freely download my command line Perl script here. It’s released under the GNU General Public License v3.

It’s a very simple tool that works on any system (Mac, Linux, Windows). It takes 2 arguments on the command line:

  • the path and name of the CSS file to minify and
  • the path and name of the output file.

To use it on any “UNIX like” system, remember to give the script the execution rights:

chmod 744

then enter the following command to minify your CSS:

./ input.css output.css

you should be presented with some statistics on success.

On Windows systems you’ll certainly need a Perl interpreter. I use myself Strawberry Perl but you can choose any other interpreter. To trigger the script on the command line type in:

c:\path_to_Strawberry_Perl\perl\bin\perl.exe input.css output.css

One last word about this tool … it is strictly provided for your convenience, so don’t expect me to debug it for you. It’s released under the GNU GPL v3, you can get the full source code so please do it yourself.
As a corollary don’t ask “it doesn’t work for me what should I do?” in the comments. It’s no rookie subject, don’t expect me to explain about UNIX file systems permissions or how to use Strawberry Perl for instance. There is plenty of documentation available on the web so use your Google talent and the power of your brain :-).

Other Speed and SEO wizardry

CSS minification is only one example of what can be achieved to speed up a web site. The most impactful technique would certainly be first to reduce the number of HTTP requests needed to retrieve all the elements on your page (images, CSS files, javascript files, external data, …). Not only does It save time on network latency but also globally on the payload transfered by limiting the number of additional TCP/IP and HTTP headers. Now if you want to go deeper with the speed subject here are a few trails for you to follow:

High Performance Web Sites by Steve Souders

Finally I point out 2 videos of Steve Souders that you can either find on his website (among other interesting videos) or on Youtube:


I hope you’ve enjoyed this topic and have found it useful. I’d be happy to come back to the speed subject if you’d like me to. But what about you? Any minification rules that you heard of that I missed or forgot mentioning? Do you know any proven techniques that drastically improve the responsiveness of web sites? Any recommendation for CSS minifying tools? Please fill free to comment.


Entry filed under: Web Development. Tags: , .

Book review: “Windows 7: the missing manual” by David Pogue Super sleek CSS3 only sliding menu tutorial

1 Comment Add your own

  • 1. Abhijit V. Chaore  |  August 9, 2010 at 10:21 am

    Congratulations for having a beautiful baby girl and thanks for this article. It shows some basic useful tricks that we – web designers- must follow in our practice. Wishes and thanks again.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


June 2010
« Apr   Jul »

Most Recent Posts

%d bloggers like this: