<!-- START POST CONTENT -->
I stumbled upon this trick not too long ago when I was looking for ways to maximize the efficiency of my websites, and reduce the footprint a little. When I am developing css, my preference is to keep the code in a readable format, so I prefer something like:
p { float:left;
display:block;
font-size: 2em !important;
background: #FFF url('/dev/../images/bg.png') no-repeat 0 0;
padding: 10px;
width: 300px !important;
margin: 0px;
border: 1px solid #000;
}
Yeah, I know this method probably immediately kicks from the ranks of the CSS jedi, but I find that my workflow goes much smoother when the code is more readable. The way I see it, formatting it like this is like code indenting, and even if making it more readable saves me a fraction of a second per read, then it probably saves me 10-20 seconds a day! That is almost 2 full minutes a week!
Anyway, when you build it out this way, and wind up with hundreds of css classes on a site, it does tend to generate a lot of whitespace in the files, which of course can add crucial kilobytes to your page footprint. So, in my travels I ran across the following php script:
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}
include ('layout.css')
ob_end_flush();
This is known as the Reinhold Weber method, and what this basically does is remove all of your CSS comments and whitespace for all of the files that you specify upon request of the file itself. All you need to do is ensure that this script is added to a master css file, and then include that file in your web template header.
I do understand that this does add some server overhead per request based on execution of the php, but if I can write the CSS however I want, comment it how I like to, etc. and have the rendered version be super stripped down, then for me that is perfect.
There are a couple of caveats here, though. You will need to make sure that you can include PHP code in CSS and that it will be parsed, so you will need to either make sure that your provider handles this, or if you have access to the .htaccess file on your site, you can include this to allow php to see css:
######### Begin - Handle PHP in CSS files ##########
AddType text/css .css
AddHandler application/x-httpd-php .css
########## End - Handle PHP in CSS files ##########
You may also run into problems with the mime type for CSS files then, so you will need to add the following to the top of the CSS files that you don't include in the script:
header('Content-type: text/css');
That is pretty much it - good luck.

