Skip to content

Instantly share code, notes, and snippets.

@clipperhouse
Created September 7, 2011 17:50
Show Gist options
  • Save clipperhouse/1201239 to your computer and use it in GitHub Desktop.
Save clipperhouse/1201239 to your computer and use it in GitHub Desktop.
CSS minifier in one line
var minified = Regex.Replace(css, @"\s*([,>+;:}{]{1})\s*", "$1").Replace(";}", "}");
// ...where css is a string containing valid CSS
// There are several ways to optimize this; I would use a compiled regex and
// put it in an extension method for ease of use
public static class Extensions {
static Extensions() // static constructor
{
_cssregex = new Regex(@"\s*([,>+;:}{]{1})\s*", RegexOptions.Compiled);
}
private static Regex _cssregex;
public static string MinifyCss(this string s)
{
if (s.IsNullOrEmpty())
return s;
return _cssregex.Replace(s, "$1").Replace(";}", "}");
}
}
@NickLarsen
Copy link

Works well only 2 things I noticed, it doesn't remove comments and it messes with quoted text in content rules.

ul.fortunes > li:after { content: ", in my pants."; /* lolz */ }

@clipperhouse
Copy link
Author

Good points! The comments should be easy to regex out; the literal content less so.

How would you go about the literal stuff? Replace each instance with a placeholder token, minify, then re-replace the tokens with original content?

@NickLarsen
Copy link

Quotes cannot be nested, so however you solve the block comments problem should work equally as well for quoted content. You might have to run multiple passes however(?) because there could be a lone quote inside of a comment.

@clipperhouse
Copy link
Author

There’s a difference between the comments and the quoted stuff I think. Comments can be wiped out with little consideration for what’s in them. The quoted content needs to be “taken out of harm’s way”, then minify everything else, then put it back verbatim. An escaped quote within content would be just enough to make it a PITA. :)

(Yes, it would be a few distinct passes.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment