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.

Comments


Comments are closed