Efficient stylesheet minification in C#

Feb 28, 2010

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.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (6) -

Gunnar
Gunnar Estonia
3/1/2010 2:21:04 PM #

Does this method do the best minification you got or is it just demo? If it is just demo then can you post the code that gives maximum results?

Mads Kristensen
Mads Kristensen Denmark
3/1/2010 2:44:44 PM #

No, this is the code that gives you better minification than YUI Compressor. I've just made it more readable by having the regular expressions inlined in the method.

Mike Borozdin
Mike Borozdin United Kingdom
3/2/2010 3:56:33 AM #

Frankly, I would use a StringBuilder here, because String is immutable and in fact you're creating 7 objects of the String type here.

krishna
krishna United States
3/2/2010 5:34:19 PM #

Interesting post.

@Mike, I would not worry about using StringBuilder (not that it would be a huge change) since this would not matter in a case of one time execution for minification. I learnt from my experience that I should not optimize everything i come across, it just kills ur time for very small benefit.

Prashant
Prashant India
3/2/2010 11:24:40 PM #

How I can use this code for my website's stylesheet. I have a file style.css I want when someone request my page then it will be automatically minified and served to the client.

How is it posisble in asp.net 3.5?

kad1r
kad1r Turkey
3/10/2010 2:54:11 AM #

+1 Prashant. I need to know how we use this code?

Pingbacks and trackbacks (1)+

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.