Compress CSS Stylesheets to Save Download Bandwidths


Page loading speed is very important as it has large impacts on the user experiences. It also affects the SEO scores as search engines favor faster websites. The CSS (Cascade Style Sheets) are now almost used on every websites. The css controls the way pages look like and often can be included in the html pages by three methods.

CSS Background

The first one is to use the HTML tag attribute style that defines the styles for that particular HTML object. For example, the following forces the span to be in red color.

<span style='color: red'>Hello, world!</span>

You can’t do much optimisation by using this method, and in fact, it is not recommended to include CSS this way as it is not easy to separate the styles from the pure HTML code later.

The second method is to put style sheet within style tag placed within the head section. So you will have something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<style type="text/css">
  span {
    color: red;
  }
  span .class {
    color: blue;
  }
  span #id {
    color: black;
  }
</style>
 
<!-- Three methods to use corresponding styles -->
<span>Hello, world (red)!</span>
<span class='class' >Hello, world (blue)!</span>
<span id='id' >Hello, world (black)!</span>
<style type="text/css">
  span {
    color: red;
  }
  span .class {
    color: blue;
  }
  span #id {
    color: black;
  }
</style>

<!-- Three methods to use corresponding styles -->
<span>Hello, world (red)!</span>
<span class='class' >Hello, world (blue)!</span>
<span id='id' >Hello, world (black)!</span>

The third method is similar, but to put all the style-related code in a separated *.css file (external) and whenever you need it in a page, just include it like this:

1
<link href="style.css" type="text/css" rel="stylesheet">
<link href="style.css" type="text/css" rel="stylesheet">

This is recommended as the browsers will normally cache the external CSS files (if they are still updated). Also, there will be a separate thread downloading the external css file in parallel, which shortens the download speed and hence increase the site loading speed.

Another obvious advantage by using this method is that, you just have to update one css file and it will affect several pages at the same time as long as they include this css file.

CSS Compression

Now, the thing you need to know is that, like most programming languages, you can compress your css code by removing extra whitespaces, line breaks, extra semi-commas and the comments. This shrinks the file size.

For example, the uncompressed CSS code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#mail form input.btn
{
    color: blue;
    background:white;
}
#mail #error
{
    color: red;
    background:yellow;
}
#mail #working
{
    color: black;
}
#mail .nor
{
  border:0px;
}
#mail .onv
{
  border:1px dotted;
}
#mail form input.btn
{
	color: blue;
	background:white;
}
#mail #error
{
	color: red;
	background:yellow;
}
#mail #working
{
	color: black;
}
#mail .nor
{
  border:0px;
}
#mail .onv
{
  border:1px dotted;
}

which will be compressed into:

#mail form input.btn{color:blue;background:white}#mail #error{color:red;background:yellow}#mail #working{color:black}#mail .nor{ border:0px}#mail .onv{ border:1px dotted}

You can use the following PHP function that does this job exactly.

1
2
3
4
5
6
7
8
9
10
11
12
13
  function compressCSS($css) {
      return
          preg_replace(
              array('@\s\s+@','@(\w+:)\s*([\w\s,#]+;?)@'),
              array(' ','$1$2'),
              str_replace(
                  array("\r","\n","\t",' {','} ',';}'),
                  array('','','','{','}','}'),
                  preg_replace('@/\*[^*]*\*+([^/][^*]*\*+)*/@', '', $css)
              )
          )
      ;
  }  
  function compressCSS($css) {
      return
          preg_replace(
              array('@\s\s+@','@(\w+:)\s*([\w\s,#]+;?)@'),
              array(' ','$1$2'),
              str_replace(
                  array("\r","\n","\t",' {','} ',';}'),
                  array('','','','{','}','}'),
                  preg_replace('@/\*[^*]*\*+([^/][^*]*\*+)*/@', '', $css)
              )
          )
      ;
  }  

The above short and concise function uses Regular patterns to match corresponding extra white spaces, line breaks etc. You can then use file_get_contents and file_put_contents functions in PHP to update the CSS file, but make sure you have a backup of the files first.

I have a folder that stores uncompressed CSS files, and I have a PHP script that converts in batch from these files to the compressed ones using the above PHP function. And finally, in my PHP pages, I always refer to these compressed CSS files. It works just like a charm.

Click [here] for a online PHP Utility Page that converts the CSS style sheet, which is a handy tool.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
788 words
Last Post: How to Create a Picture By Changing Cell Colors in Excel, using PHP and VBScript?
Next Post: The Childhood Memory - Subor Famicom Clone SB-486D (Xiao Ba Wang)

The Permanent URL is: Compress CSS Stylesheets to Save Download Bandwidths

Leave a Reply