How To: Optimize Your CSS Even More

March 18, 2007 · 107 comments

Over the summer I wrote a post called 5 Ways to Speed Up Your Site that went through some basic tips for getting your site to load faster. I mentioned enabling gzip compression in WordPress and using services that remove the whitespace from your CSS, effectively “compressing” it. Now, I’ll go a bit more in-depth with a simple, yet powerful, PHP method of compressing your CSS.

What We’re Doing

The WordPress method of compression gzip’s your site’s markup, but it doesn’t go so far as compressing your linked stylesheets. To get the benefit of a compressed CSS file (or more, if you have several), I’m going to go a bit deeper by adding this compression directly on each CSS file.

Things You Should Know

All forms of compression, including this PHP method, will utilize a tad of your server’s CPU to compress data. For most this is negligible, but if you know that you are on a flaky, shared-server-using webhost you might rethink using compression on your site. But I mean, it would have to be a flaky webhost.. a $5/year host as from what I’ve seen most decent servers can handle compression no problem.

Also, not every browser supports gzip compression. However, you’d have to be running a very old browser for that case to appear. Kyle Neath tells me that IE 4+, Netscape 4+, Opera 5+ and all versions of Safari and Firefox support gzip compression, so I would say that it is very safe to go ahead with using gzip compression in terms of compatibility.

Edit: The method of gzip compression I will be pursuing utilizes ob_gzhandler which is smart about compressing data..

Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept (”gzip”, “deflate” or none at all) and will return its output accordingly. All browsers are supported since it’s up to the browser to send the correct header saying that it accepts compressed web pages.

Gains

With compression you save bandwidth by having smaller file sizes. For example, my already whitespace-free CSS file was around 9kB before compression. After, it weighed in at only 2.4kB. While that is a great compression rate, let me show you the difference on your typical CSS file. Using digg’s global CSS file as an example – before compression the CSS was 26.3kB and after compression it was only 6kB. Amazing stuff.

Okay Already, Show Me How!

First off, make a copy of your current CSS file and add the suffix “.php” to the file name. If your CSS file was named style.css your new file would be named style.css.php (don’t include this period to the right > ).

Next, update your CSS link to reflect this change. Note: Don’t copy and paste the any of the code below – my blog displays quotes as smart quotes instead of regular ones and this will mess it up. Just type it as you see it.

Before

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

After

<link rel="stylesheet" type="text/css" media="screen" href="/style.css.php"/>

Now to the real part. Open up your style.css.php, or whatever you named it, file and add the following snippet of PHP to the very top:

<?php if(extension_loaded('zlib')){ob_start('ob_gzhandler');} header("Content-type: text/css"); ?>

Then, add the next line to the very bottom and save the file.

<?php if(extension_loaded('zlib')){ob_end_flush();}?>

That’s it! Refresh your site and check it out.

How It Works

The first part of the PHP code checks to see if your server’s PHP installation supports zlib, which is required for the gzip compression we are trying to attain. If that’s all fine and dandy, output buffering begins processing with ob_gzhandler, which creates gz-encoded data if supported by the user’s browser. The last line stops the output buffering and sends the contents of the buffer to the user. It is debated whether or not ob_end_flush() is actually required since it is apparently called automatically by PHP at the end of the script execution, however I kept it in there for good measure.

If you did just the output buffering, this method wouldn’t work since the browser doesn’t know how to parse it. That’s why the header of content-type text/css must be sent out.

What Do You Think?

As of now, this blog’s homepage comes in at 27.6kB from its already lightweight 34kB. If I didn’t have those three sponsor graphics in my sidebar, it would only be about 15kB.

After you have dealt with compression and saving images for the web, the next thing would be optimizing database queries.. but that’s another article or series of articles in itself.

What do you do to ensure that your site runs and loads as fast as it can?

{ 64 trackbacks }

links for 2007-03-18 « kobak del.icio.us könyvjelzÅ‘i
March 18, 2007 at 6:12 pm
Common web myths: Optimizing CSS & Javascript - Warpspire
March 18, 2007 at 6:57 pm
Optimize Wordpress loading times » gHacks tech news
March 19, 2007 at 2:22 am
Optimize Wordpress loading times - Computer Forums
March 19, 2007 at 7:03 am
Compressed CSS | David Paul Robinson
March 19, 2007 at 5:39 pm
煎蛋 » 本月 CSS 小甜点
March 20, 2007 at 9:02 pm
Switch-Case / Blog Archive / Links for 3/21/07 [my NetNewsWire tabs]
March 21, 2007 at 8:04 am
Creative Commodity » Blog Archive » Optimizing Your CSS
March 21, 2007 at 11:35 pm
Bookmarks (22.03.2007) | Fabu(TM)
March 22, 2007 at 4:13 pm
CSS dosyalarınızı gzip ile optimize edin - Günlük Haftalık Aylık
March 23, 2007 at 9:12 am
在线网页分析工具 - Nicky's blog
March 23, 2007 at 11:52 am
Sweetblues’ Inspiration » Optimize My CSS
March 24, 2007 at 2:02 am
压缩你的JS和CSS代码 - Nicky's blog
March 25, 2007 at 12:59 pm
michaelmuller.net | Diseño y Desarrollo Web
March 25, 2007 at 11:06 pm
在线网页分析工具
March 26, 2007 at 4:46 am
mcdave.net » links for 2007-04-05
April 5, 2007 at 2:19 am
WEBclusive » Blog Archive » Enkele goede handleidingen op het gebied van CSS
April 11, 2007 at 7:39 am
Why My Wordpress Site Is So Much Faster Than Yours by Elliott Back
April 15, 2007 at 9:31 pm
煎蛋 » 如何提升 Wordpress 性能
April 16, 2007 at 9:49 pm
sams weblog » Blog Archive » Schnelleres Wordpress
April 18, 2007 at 6:11 am
Good List Of WordPress Optimisation Links | Connected Internet
April 19, 2007 at 9:45 pm
PaulStamatiou.com
April 22, 2007 at 5:06 pm
h4x3d.com | Compressing moo.tools (javascript) even further
April 25, 2007 at 5:48 am
Rick Retardo » Blog Archive » Good List Of WordPress Optimisation Links
April 30, 2007 at 1:13 pm
IAMWW » Spring 2007 CSS Reboot of IAMWW.com
May 1, 2007 at 2:35 pm
Optimizar los archivos CSS at Blëg
May 12, 2007 at 5:58 pm
Javascript, PHP, CGI, Perl, ASP, Vbscript, Ajax articles, resources and programming tutorials
May 16, 2007 at 6:21 pm
blog need for speed
July 9, 2007 at 3:03 pm
CSS: Domptez IE (Et les autres…) - JBJ’s Blog
August 6, 2007 at 5:29 pm
TechZilo
August 20, 2007 at 5:59 am
iHao Press » 压缩代码让BLOG飙起来
September 5, 2007 at 10:10 pm
My Habari
September 23, 2007 at 1:16 pm
Archivos CSS mucho más pequeños ~ Gran Impetu
September 24, 2007 at 5:53 pm
Comprimir las hojas de estilo (CSS)
September 27, 2007 at 8:15 am
Le blog de Vincent Battaglia » En vrak - 61
October 4, 2007 at 2:13 pm
Trinidad Servicios Informaticos » Blog Archive » Optimizando los Archivos CSS
January 16, 2008 at 8:21 pm
» Blog Archive » CSS dosyalarınızı gzip ile optimize edin
January 21, 2008 at 10:51 am
5 Ways to Speed Up Your Site « kun’z
March 11, 2008 at 7:25 pm
Onyx Design Weblog
April 9, 2008 at 4:03 am
IndoProTech.com
July 2, 2008 at 4:10 am
在线网页分析工具 - 英文站采集 SEO优化 Adsense广告配置
July 8, 2008 at 2:48 pm
Css Dosyalarını GZip İle Optimize Edin « RoyaLTurK WordPress
July 10, 2008 at 9:45 am
WordPress中你的style样式文件有多大 | Smartr.cn
July 23, 2008 at 8:23 pm
Te Ayudo- Compresión de archivos en Wordpress. Reduciendo el ancho de banda.
August 14, 2008 at 5:49 pm
7 Principles Of Clean And Optimized CSS Code | CSS | Smashing Magazine
August 18, 2008 at 7:50 pm
7 Principles Of Clean And Optimized CSS Code | [w3b]ndesign
August 19, 2008 at 3:19 pm
7 Principles Of Clean And Optimized CSS Code | Proba
August 19, 2008 at 6:27 pm
7 Principles Of Clean And Optimized CSS Code « ATI - All Things Interesting
August 20, 2008 at 8:22 am
Vieno » Blog Archive » 7 Principles Of Clean And Optimized CSS Code
August 21, 2008 at 5:37 am
7 Principles Of Clean And Optimized CSS Code
August 22, 2008 at 1:54 am
对Wordpress的几点优化 - Allen's blog
August 23, 2008 at 8:59 pm
sql database info for professionals » Blog Archive » 7 Principles Of Clean And Optimized CSS Code
August 27, 2008 at 6:29 am
7 Principles Of Clean And Optimized CSS Code | Evolution : weblog
October 31, 2008 at 12:44 am
Upmedia.dk | weblog for Uffe Petersen » 7 Principles Of Clean And Optimized CSS Code
November 10, 2008 at 7:40 am
断峰狼的博客 » [网页制作]在线网页分析工具
November 26, 2008 at 2:17 am
整理及优化CSS代码的7个原则 - 网络应用与资讯
December 8, 2008 at 11:06 pm
3 ways to compress CSS files using PHP
December 18, 2008 at 11:45 pm
3+1 formas de comprimir nuestro CSS desde PHP | aNieto2K
January 26, 2009 at 2:48 pm
Net Feast» Blog Archive » 3 ways to compress CSS files using PHP
February 10, 2009 at 10:16 am
Compress CSS / JS(Javascript) files Using PHP | The Code Dreamer
March 2, 2009 at 4:27 am
Simple tricks to speed up your WordPress website. :: Christopher Ross
April 20, 2009 at 10:46 am
整理及优化CSS代码的七个原则 | jsssc
April 21, 2009 at 9:02 pm
How To: Optimize Your Apache Site with Mod Deflate - PaulStamatiou.com
April 23, 2009 at 5:18 pm
Yaaahaaa 首页 » Blog Archive » 如何提升 Wordpress 性能
May 19, 2009 at 11:18 pm

{ 43 comments… read them below or add one }

1 menghua March 18, 2007 at 7:37 am

The codes won’t show up in feeds. Now wonder I can’t understand what it’s all about. :) Thanks for the tips!

Reply   More from author

2 Julian Bennett Holmes March 18, 2007 at 10:38 am

Yeah, I get a completely blank page in NewsFire.
Weird.

Good tip though, thanks.

Reply   More from author

3 Paul Stamatiou March 18, 2007 at 11:08 am

Yeah I have no idea why it’s doing that..

Reply   More from author

4 Arjun March 18, 2007 at 11:18 am

Oh this is nice

Reply   More from author

5 Dustin Bachrach March 18, 2007 at 11:25 am

Very cool script. I’m adding this to all my pages now.

Reply   More from author

6 Dustin Bachrach March 18, 2007 at 11:35 am

By the way. If anyone copy and pasted Paul’s code and now is getting a blank display, be sure to go back and change the ” (quotes) in your php file. Just delete them and retype them in your text editor. Seems like WordPress is throwing up smart quotes or something and that interferes with PHP code.

Reply   More from author

7 Paul Stamatiou March 18, 2007 at 12:35 pm

Yeah that’s an issue with my code plugin. =/

Reply   More from author

8 Anonymous Coward March 18, 2007 at 1:30 pm

I do the same thing with my CSS files. You should also probably send out the charset like this: header(”Content-type:text/css;charset=utf-8″). I also enable caching by outputing a last-modified header and returning a 304 if the representation hasn’t changed. In addition, you can send an Expires or Content-control: max-age header to specify how long the file can be cached.

Reply

9 Derek Punsalan March 18, 2007 at 1:59 pm

If anyone finds a plugin that does not spit out smart quotes for code, do share. I think this is something that a lot of WordPress users are looking for. I used to use the same plugin Paul, but after seeing that it basically rendered the code snippets useless, I disabled and went back to using <code> around web safe converted code – Postable.

Reply   More from author

10 Ash Haque March 18, 2007 at 5:41 pm
11 Paul Stamatiou March 18, 2007 at 6:08 pm
12 Ronald Heft March 18, 2007 at 9:31 pm

For those with the Smart Quote problem, I’ve always used this plugin and never had a problem.

Reply   More from author

13 Brajeshwar March 19, 2007 at 3:55 am

Why not mess with the css but do the same with the addition of 2 separate files. I find this cleaner

1. Drop a .htaccess in your css folder or just add this to your main .htaccess

AddHandler application/x-httpd-php .css
php_value auto_prepend_file gzip-css.php

2. of now, you will need the gzip-css.php with the following code

Reply   More from author

14 Patrick March 19, 2007 at 9:35 am

Paul,

The plugin you linked is nice, but it has an insane amount of file inclusions.

I just tried out “SyntHihol”, http://www.indyjt.com/software/synthihol/SyntHihol.zip

It highlights whatever language you define, using GeShi. Doesn’t include any external JS or CSS files as far as I can tell. Best of all, it’s easy to toggle the styling.

For a quick demo, see: http://patrickmn.com/2007/03/19/appetizer-easiest-proxy-server-ever-with-python-and-twisted/

Reply   More from author

15 Matthew R. Miller March 19, 2007 at 2:19 pm

This is a good tactic, but it’s adding load to your web server by having to do this every request. It would be more efficient to use caching or compress it once and make it a static css file.

http://www.codeandcoffee.com/2007/01/19/how-to-compress-your-css/

Sure the load isn’t much until your page hits spike, like on popular blogs. In situations where you blog and data is dynamic, it’s best to make PHP and your database work as least as possible… dynamic is only good to a certain extent and for data that is changes a lot.

Reply   More from author

16 Paul Stamatiou March 19, 2007 at 3:04 pm

@matthew – the site you liked to talks about css compressor which only removes whitespace, comments and things like that. That’s much different than this gzip compressing, although I do use both methods. But in general, you’re right – cache where and when you can.

Reply   More from author

17 Matthew R. Miller March 19, 2007 at 3:08 pm

Current, I know it only removes whitespace… but you could cache your gzip results so the server and PHP does not need to do this every page hit.

Reply   More from author

18 Lorelle March 20, 2007 at 1:36 am

Writing code in WordPress is a pain, but fixing your code is actually very easy, and essential to avoid all the whines and complaints. There are some simple instructions in WordPress.com Blog Bling: Signatures and Writing Code in the second half of the article that will help, along with some online tools for fast converting if you don’t want to do a little search and replace in a text editor.

I post code on my blog constantly, and so I’m very familiar with this issue.

Very great tips. I hope my tip helps you make them better. ;-)

Reply   More from author

19 nathan March 20, 2007 at 10:45 pm

umm why not just gzip the css? the http 1.1 spec allows for gziped data… set the mime type to x-html it should still render as css though.

Reply

20 Paul Stamatiou March 20, 2007 at 10:47 pm

nathan – there are multiple ways of gzipping your CSS. the way you mentioned works just as well.

Reply   More from author

21 Ajay March 21, 2007 at 12:04 am

Paul, is there some option to have it sitewide for all CSS files and not just the style.css file??

Reply   More from author

22 tash March 21, 2007 at 2:37 am

Awesome, I used this and the css-compress plugin on my blog. Now I have my shoutbox plugin sending itself compressed. Before it was one of the biggest code that the browser had to download

Reply   More from author

23 Mike Papageorge March 22, 2007 at 4:24 am

Neat Trick Paul!

For something more sophisticated, which may be useful in other situations:

The Definitive Post on Gzipping your CSS

Reply   More from author

24 Mike Papageorge March 22, 2007 at 4:34 am

Right, one more thing, you may want to send a full set of headers with what you are doing, or else you risk having the browser *not* cache the CSS file and request it every time. I did a bunch of testing when I looked at this back in 2004 and most of the browsers only cached the CSS file if it came with the proper expires headers.

See the file I linked above for the details.

Reply   More from author

25 Ajay March 22, 2007 at 4:38 am

Mike thanks for pointing this out… Am looking at the tutorial now. Would this also be the case for other type of files, like js files?

Reply   More from author

26 Mike Papageorge March 22, 2007 at 5:08 am

Hey Ajay,

For sure. Basically, what’s happening here is the file is being “served” by PHP, rather then Apache (or whatever), so the headers are no longer being handled by the server, but by the scripting language.

If you have a local setup that you can test on, try this out locally and check the log files (I played with this stuff here, ). You will see if your caching is working etc.

Reply   More from author

27 Ajay March 22, 2007 at 5:43 am

I have a local setup, so will take a look.

But, I really like the gzip solution.

Reply   More from author

28 Vladimir Nikolic March 24, 2007 at 2:44 pm

This is not great.
IT´S PERFECT!!!

I reduced my site from good 43KB and bad 42HTTP requests to
unbelievable 29KB and only 18 HTTP requests.
This is stunning!
I am searching non stop for methods to reduce site loading time.
At first the site had about 92KB and with every new method I reduced it
a bit.
Thank you Paul!

Reply   More from author

29 Michael Müller March 25, 2007 at 8:54 pm

Great post. Thank you for the info. I’ll make a reference about it on my blog.

Reply   More from author

30 jez April 25, 2007 at 5:04 am

using it. loving it. thanks!

Reply   More from author

31 Markus June 29, 2007 at 8:47 am

Great! Thanks for this how to! …markus

Reply   More from author

32 fromvega July 30, 2007 at 12:38 pm

Hello, it might be simpler just to do:

instead of checking for the library. ‘@’ should suppress the warning message!

Reply   More from author

33 Luis August 31, 2007 at 10:14 am

Do you really think that doing an unique js file, compressing it with JSmin (or similiar) and doing a gzip of that file really worth?

Because all that parsing functions, joining, parsing and compressing here and there would result in a greater load time for this files, I mean, would you do a simple gzip?

Reply   More from author

34 Patrick Burt September 5, 2007 at 9:56 am

Great resource m8, I’m going to work at implementing this on my webpage.

Reply   More from author

35 Steve September 24, 2007 at 5:27 am

Nice article. I’ve seen it in a couple of places before but never seen the code behind it.

Cheers for the post

Reply   More from author

36 Carlton Bale September 30, 2007 at 2:42 pm

I thought I would add that the CSS Compress WordPress Plugin not only compresses the CSS file, but also compresses the images referenced within the CSS file and sends everything to the client in a single gzip file.

This eliminates the need to combine images into a single file and use image maps, because the number of HTTP requests would be the same either way. I verified this plugin by testing my page under several scenarios using WebSiteOptimization.com. Unfortunately, the plugin works only on the main template CSS file, not any CSS files used by plugins. If you’re using WordPress, the CSS-compress plugin is an easy way improve performance.

Reply   More from author

37 Cesar Gonzalez April 4, 2008 at 7:04 pm

Thanks, I’ve been looking for how to gzip my CSS. This rocks.

Reply   More from author

38 moserw July 18, 2008 at 9:03 pm

This looks very interesting. Have used the Icey CSS compressor, but never have gone into depth on this subject since I am not a programmer. You make it sound so easy with simple instructions. Much appreciated.

Reply   More from author

39 Carlton Dickson August 19, 2008 at 8:17 am

Thanks, I’ll definitely tag this page for future reference, will definitely come in handy.

If you are having trouble displaying code in Wordpress I have written a post (http://carltondickson.co.uk/2008/03/02/displaying-source-code-in-wordpress-post/) that could help, I would definitely recommend the Google Syntax Highlighter (http://wordpress.org/extend/plugins/google-syntax-highlighter/) admitedly it does include all highlighters C++/XML/JAVA but these can easily be removed using the plugin editor and removing the script tags containing the brushes you don’t need.

@Vladimir Nikolic It’s always nice to discover ways to reduce the page load and performance of your pages….I would urge you to install YSlow, it’s a firefox plugin for another firefox plugin – firebug. They reguarly talk about ways to serve pages faster, I checked your site and there are definitely plenty of things that you could do to reduce the page size even more, give me a mail if you need any help :)

Reply   More from author

40 Kit Barker December 16, 2008 at 8:15 am

Well done on a great article.

I’ve read a few articles on this topic recently and one thing I’ve been wondering is why none of them seem to mention the increase in processor resource required, both server side and client side, for compression and de-compression.

I guess my question is this: do you think the bandwidth saved is worth the processing time lost?

Reply

41 Param December 17, 2008 at 8:40 am

Hello Expert’s,

I was using the same what you mentioned Before and After. But the thing is that Before is taking less time to load as compare to After.

For Better Waiting Response

Reply

42 Nick January 23, 2009 at 6:41 pm

this thing dont work on me… so maybe need better demo or something to download so i can understand this by how this stuff work better..

Reply

43 septianw March 25, 2009 at 2:10 pm

i dont have any ide to do, but i’ll try this one.

thanks for your trick.

Reply   More from author

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post: ActiveCollab, Basecamp and Goplan Comparison

Next post: Refresh Houston/WordPress Meetup