Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Thursday, September 29, 2011

Efficient stylesheet minification in C#

I 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.

No comments:

Post a Comment