Compress CSS on the fly

Oct 1st, 2007 by Jared Schwager , ,

In an attempt to further speed up loading times for Grupenet, I decided to compress (remove spaces and comments) my CSS stylesheet. However, instead of applying compression directly to the original file, why not add some PHP code to the stylesheet to compress the CSS dynamically when it is loaded on the server? This way all readability is maintained when editing the original file. This way you can add as much commenting as you need to keep your CSS more organized.

Step 1

Create a new file called .htaccess in the same directory your stylesheet is in. Open your newly created .htaccess file and add the following lines:

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

(Replace style.css with the filename of your stylesheet)

Step 2

Open up your stylesheet and add the following to the top of your stylesheet:

header('Content-type: text/css');
function compress($buffer) {
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;

Now add this to the bottom of your stylesheet:

<?php ob_end_flush(); ?>

Step 3

That’s all there is to it! Now open up your browser and point it to your stylesheet. All the comments and spacing should be removed, and it should look something like this.