Minify CSS Tutorial

Your website has CSS files and they consume bandwidth. You can reduce this by minifying the stylesheets, removing whitespaces and excess characters. CSS Tidy is an excellent and simple option for minifying style sheets. This document has instructions and benchmarks.

~~~ Minify CSS Example -- csstidy.exe ~~~               
    Size is in bytes.                                   
    Combining GZIP and minification was very effective. 

style-a.css [before]:           71300 bytes
style-a.css.gz:                 11396 bytes

style-b.css [csstidy highest]:  54171 bytes
style-b.css.gz:                  9626 bytes

style-c.css [csstidy remove_;]: 53692 bytes
style-c.css.gz:                  9616 bytes

Download CSS Tidy

Here you need to go to SourceForge, a site that hosts open-source projects, to download the csstidy.exe program. This program is run on the command line, and doesn't have a GUI. It isn't being developed further, but it is complete.

Visit csstidy.sourceforge.net.

Move files to the C:\ directory

In the file "csstidy-1.3-exe.zip" you have downloaded, extract the EXE and place it in your C:\ directory. You can place it anywhere, but for this tutorial, we will use the top-level C:\ directory. In Windows Vista, you may need to change your administrator options.

Next steps. Find the CSS files you want to minify. For this example, I use a CSS file called "style-a.css". This is a stylesheet I downloaded in Firefox from a big website. Here I place it in the C:\ directory alongside the csstidy.exe file.

Run commands

In Windows Vista, open your Start menu and type "cmd" in the search box and press Enter. In Windows XP, go to Programs -> Accessories -> Command Prompt. The black command window will appear. Next, type in the following commands into the command line. Alternatively, you can copy these commands and right-click to paste them into the command line.

C:\csstidy.exe C:\style-a.css --template=highest C:\style-b.css
<Enter>

Selectors: 740 | Properties: 1983
Input size: 69.63KiB  Output size: 52.901KiB  Compression ratio: 24.02%

Another option. You can also use the --remove_last_; option if you want to. Here is the output when I type in that command.

C:\csstidy.exe C:\style-a.css --template=highest --remove_last_;=true C:\style-c.css
<Enter>

Selectors: 740 | Properties: 1983
Input size: 69.63KiB  Output size: 52.434KiB  Compression ratio: 24.7%

Measure results

The results from the minification were that the style sheet was reduced by 24.02%, and 24.7% in the second test. This means that the stylesheets require 24% fewer bytes, which will save you money and improve the performance of your web site significantly.

Note. Removing the trailing semicolon in each property list, with the --remove_last_; option, saved more bytes. However, sometimes when you have GZIP-compressed the minified stylesheet, this option will result in larger sizes. This is because GZIP searches for patterns, and having the trailing semicolon can improve this algorithm's effectiveness.

Command-line arguments to csstidy.exe

Here we see the syntax for the CSS Tidy executable on the command line, which you can see by running it with no options, such as running it with "C:\csstidy.exe".

Usage:

csstidy input_filename [
 --allow_html_in_templates=[false|true] |
 --compress_colors=[true|false] |
 --compress_font-weight=[true|false] |
 --discard_invalid_properties=[false|true] |
 --lowercase_s=[false|true] |
 --preserve_css=[false|true] |
 --remove_bslash=[true|false] |
 --remove_last_;=[false|true] |
 --silent=[false|true] |
 --sort_properties=[false|true] |
 --sort_selectors=[false|true] |
 --timestamp=[false|true] |
 --merge_selectors=[2|1|0] |
 --case_properties=[0|1|2] |
 --optimise_shorthands=[1|2|0] |
 --template=[default|filename|low|high|highest] |
 output_filename ]*

Description of table. Next we see a table that describes these command-line options. I have bolded the options that I have found to result in the best compression. For quick use, read the section on --template.

--allow_html_in_templates
I haven't used this, but it is worth a try if you have embedded HTML.
[Rarely needed]

--compress_colors
Set this to true or false. On the highest compression mode, this will be enabled
automatically, so you don't need to change this.

--compress_font-weight
Set to true or false. In CSS, you can change "font-weight:bold" to "font-weight:700",
for example. This is enabled automatically on highest compression.

--discard_invalid_properties
Common invalid properties are "filter" and "-moz-opacity". Usually, you do not
need to change this option.

--lowercase_s
Changes all selectors to lowercase. Lowercase text usually compresses better.
Don't change this option if you are using XHTML. Generally, leave this alone.

--preserve_css
No description.

--remove_bslash
Not normally needed. This isn't really related to optimization.

--remove_last_;
Removes the final semicolon in each property list. Essentially changes ";}"
to "}" in the CSS text. This can improve or decrease final compression sizes.
[Please see section on this.]

--silent
Used to control the messages outputted on the command line. Don't worry about
this.

--sort_properties
This isn't very useful, and doesn't often change the final byte size. It sorts
properties (within the {}) alphabetically. Could enhance readability.

--sort_selectors
See above.

--timestamp
This adds the date to the CSS file. Not useful for minification. In your web
site build step, you can do this in other ways.

--merge_selectors
This combines selectors (such as "h1") that have equivalent property lists (such
as "font-weight:700"). I recommend against this, as it can disrupt the results.

--case_properties
This lets you change the case for your properties (within the {} blocks). You
can achieve greater final compression ratios with all lowercase properties, but
most style sheets don't need this.

--optimize_shorthands
This changes redundant values in the CSS shorthands to be more terse. Example
output: Changed "25px 0 30px 0" to "25px 0 30px"

--template
This is the most useful option that controls the compression level. It is called
template because it changes all the previous options. It can be set to three preset
'level' values:
--template=low: Don't apply serious optimizations.
--template=high: Apply high level of optimizations, but keep each statement on a
separate line.
--template=highest: Remove all whitespace, resulting in the smallest file
size. [Note: this doesn't remove the trailing semicolon.]

Using YUI Compressor

The other good option for minifying CSS is the YUI Compressor. I plan to cover it in a separate article. It is built on top of the Java engine built by Mozilla for parsing JavaScript.

Visit developer.yahoo.com.

Using csstidy.exe in the build step

Most big sites have a build step where all the files are compiled and minified. You can write code that controls CSS Tidy and directs it to minify the CSS files at this point. My approach here is to simply use the --template=high option, and only minify the stylesheets once. The --template=high option results in fairly readable CSS text.

Improving compression rate

Here we see some ways to minify your stylesheets even better. One trick is to use the lowercase version of the font names you use. For example, use "font-family:verdana" instead of "font-family:Verdana". Lowercase text compresses better.

Minify background tip. For background colors, use the "background:blue" property style instead of "background-color:blue". This saves more bytes in your CSS files. It is also worthwhile to shorten selector text, and refactor your CSS so more of it is shared.

Minify border tip. Instead of specifying "none" on the "border:none" property, use "border:0", which means the same thing. Don't use the "px" unit on the "0", either, as it is not necessary.

Minify element selectors. For element selectors, such as "h1{...}", always use the lowercase tag name, as lowercase text compresses better with GZIP. Additionally, it is easier to read.

Minify tag names. Don't specify tag names when not necessary. Often, you can replace "div#id" with "#id", which is shorter and can reduce file size.

Use inline stylesheets

I encourage the use of inline stylesheets in <style> tags in your HTML. This saves an HTTP request, and reduces the number of operations necessary for the user to see your page. You can use PHP or ASP.NET to insert minified stylesheets into your pages dynamically.

Summary

Here we saw a tutorial for minifying and optimizing CSS files, by removing unneeded characters and line breaks. We saw the steps to use csstidy.exe on the command line. I discussed some tips on further optimizations of CSS files.

See Compress Articles.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen