SEO Egghead by Jaimie Sirovich: A blog about SEO, written for nerds, by a nerd.

Choose a Topic:

» Suggest a topic or buzz to cover; if I write about it, you'll get credit with a link in the post!

Fri
21
Jul '06

ROTD: Removing CSS Bloat

This function, comprised of a simple regular expression, will remove most of the bloat from larger CSS files.  Not that the effects are very substatial or groundbreaking, but it does save quite a few kilobytes to run things like this over your CSS and HTML.  Using mod_gzip also has a favorable effect, but this cannot hurt either.  If you find any real bugs, let me know; if it's something completely pathological and contrived, don't let me know.  I have another filter for HTML; but I'll post it another day.  Here it is:

<?

function trimCSS($str)
{
    return 
preg_replace('#(?<=[:;\w{])\s+(?=[}\w;:\#])#'''$str);
}

?>

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • Furl
  • Reddit
  E-Mail This Post/Page

2 Responses to “ROTD: Removing CSS Bloat”

  1. matt Says:

    Do you place this in your css file? And then turn on php processing for css files via htaccess?

    I've done that, but didn't really notice a difference - How can I tell if its working?

    And any chance of getting the same snippet for the html files? I'm big on reducing code bloat :)

  2. w Says:

    This regex didn't work for me for some reason. I made an alternate set that does... and also strips comments. The only thing you really need whitespace-wise is a single space after '}' and a space between CSS properties ("1px solid #000"). Everything else is bloat.

Leave a Reply