A few weeks back i found out that the method I use to minify CSS was about 5% more efficient than the YUI Compressor. I tweeted about it and was encouraged to post the code that does the actual minification.

public static string RemoveWhiteSpaceFromStylesheets(string body)

{

  body = Regex.Replace(body, @"[a-zA-Z]+#", "#");

  body = Regex.Replace(body, @"[\n\r]+\s*", string.Empty);

  body = Regex.Replace(body, @"\s+", " ");

  body = Regex.Replace(body, @"\s?([:,;{}])\s?", "$1");

  body = body.Replace(";}", "}");

  body = Regex.Replace(body, @"([\s:]0)(px|pt|%|em)", "$1");

 

  // Remove comments from CSS

  body = Regex.Replace(body, @"/\*[\d\D]*?\*/", string.Empty);

 

  return body;

}

 

The method takes a string of CSS and returns a minified version of it. The method have been modified for demo purposes, so you might want to optimize the code yourself.

I wanted to try something new this time, so I recorded my blog post as a screencast. Since I mostly write about code I thought it might be a good way to illustrate it in a video instead of in writing. It does add a new level of simplicity and understanding to the message. Please check it out and tell me if you like the video more than a regular blog post.

[vimeo:8338567]

I hope the video illustrates just how easy it is to embed images in stylesheets and also how to use the online tool for image to base64 conversion.