communication leads to understanding, so ...

Compressing your CSS Stylesheet

Whether I am coding PHP, Javascript or CSS, I always force myself to comment the code for later reference. The drawback of this is that your files will grow in weight and that can, in case of JS- and CSS-files, cost you some extra bandwidth and download time.

Now there are tools to compress your script files and stylesheets, but the problem is maintenance. Especially when you develop locally, as I do, every time when you modify your stylesheet for instance you have to run this tool to compress your file before you upload it to your live server. That didn't work for me, so I just upload the file as it is including all the comments. Until I ran into an article of Nicholas Gagne on ibloomstudios.com.

In this article he comes up with a neat solution for this problem. A few lines of PHP code including in your css stylesheet will automatically handle the compression.

This is how it works:

  • The user's browser requests the stylesheet as usual
  • The server compresses the stylesheet using PHP
  • The stylesheet is outputted to the browser

First, add this code to the very top of your css stylesheet:

<?php
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
  // remove comments
  $buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
  // remove tabs, spaces, newlines, etc.
  $buffer = str_replace(array("rn", "r", "n", "t", ' ', ' ', ' '), '', $buffer);
  return $buffer;
}
?>

The first line let's the browser know that this is a CSS stylesheet. Next, it starts the overflow buffer collection for later processing with the "compress" function. The compress function is used to remove all comments and spacing. Finally, the compressed CSS is sent to the browser.

Next, add this code to the very bottom of your CSS stylesheet:

<?php ob_end_flush();?>

Basically, this tells PHP to stop collecting output, and to run the previously specified "compress" function. After that, the compressed CSS stylesheet is sent to the browser.

To make it all work, you have to tell the server to parse the PHP code in your stylesheet. To do so put a .htaccess file in the directory where you keep your stylesheet with the following lines

assuming your stylesheet is called ’style.css’:

<Files style.css>
 SetHandler application/x-httpd-php
</Files>

All of this happens without the user ever realizing it. Best of all, it doesn't change your CSS stylesheet, allowing you to easily maintain and update it. Isn't that nice?

If you want, you can download the code here.

 |  | 21-02-2007

piXelatedEmpire wrote on 22-02-2007#1

This is terrific! Great find and share brauk.. I'm the same, I always comment everything!

David wrote on 23-02-2007#2

This is nice for our browsers but maybe not for the cpu and memory of the web server if you have a huge traffic, no? ;)

Could be David, that depends of course on the server. In particular with big stylesheets, let say appr. 1000 lines or more, testing would be sensible.

John wrote on 02-03-2007#3

There are good results from just keeping 2 copies of the css document, one for readability (not linked) and the other for destroying readibility with http://cdburnerxp.se/cssparse/css_optimiser.php .

I'm sure there are John, but it depends on how your workflow is. In my case, when I modify a file on my local webserver and it gives a good test result, I save the file to ftp and have it instantly available on the live server. So I don't have to bother with copy and paste to an external source, paste it back to a second css file and then upload the file.

Thanks for your contribution though!

John wrote on 10-04-2007#4

There is also covered ages ago here...
http://www.fiftyfoureleven.com/weblog/
web-development/css/the-definitive-css-gzip-method

Thanks for sharing John.

Sven wrote on 16-04-2007#5

Amazing !
Some PHP code into a CSS.
How can the compression be seen, brauck ?

Hey Sven, welcome to my website.

Do you have Firefox as your webbrowser? If yes, do you have the Webdeveloper Toolbar installed? If yes, just click the CSS-button, if no, you should install this add-on. Do you have IE as browser? Then install the Web Accessible Toolbar and click the CSS-button.

Philippe wrote on 17-04-2007#6

Hello brauck
thanks a lot for your answer.
I was exhausted yesterday evening : I should have a look at your own compressed stylesheet. :(
It didn't work for me.
I suppose something went wrong with the htaccess.
(maybe since there are 2 stylesheets and I first tried to compress only one)
Same player will shoot again this very evening. ;)

Sam wrote on 10-05-2007#7

Very nice trick Brauck, it helped me a lot! thank you.

Patric wrote on 22-05-2007#8

Oh, crap, Onno... Lovely find. will try this out as I have a bit of CSS, hehe... Now is this implementable in any other file aswell ? As in a .php or so ?

Christoph wrote on 15-11-2007#9

Thanks for the very nice idea - I will try it out these days, but will rather try not to compress on-the fly coz as mentioned above starting a php process for every css-request is not possible for high traffic.

cheers
chris

©2006 - 2010 hbwConsultants - The Netherlands 

CMS  • XHTML • CSS • RSS