Microsoft.AspNet.Web.Optimization Minifies Mediaqueries wrong

Yngve Bakken Nilsen

Update: The bug mentioned here is now fixed in both WebGrease (making sure there are leading spaces) and in Chrome (making sure it parses mediaqueries without leading spaces in front of keywords). However, since this is a proposal in the future CSS spec that spaces are mandatory, I'll leave the blogpost out here for future reference :) But basically, the content below is deprecated.

When minifying Media Queries with Microsoft.AspNet.Web.Optimization the leading 'and', 'not' and 'only' is missing a whitespace before the word.

It seems this might be a bug introduced in Chrome 32 m
and now it seems they fixed it

So a CSS like so:

@media (min-width: 1025px) and (max-width: 1599px) {
#circles_inner {
    width: 1080px;
    margin: auto;

Ends up being minified like this:

@media(min-width:1025px)and (max-width:1599px){#circles_inner{width:1080px;margin:auto}}

This has been working fine up until the latest version of chrome (32.*), but it seems the CSS-parsing has become stricter.

There is currently a bug/blame-game at CodePlex but I thought a dirty hack/workaround is needed anyway. Luckily we can override the default CSSMinify class. It's not elegant, but it works:

public class BundleConfig
    public static void RegisterBundles(BundleCollection bundles)
        var siteCssBundle = new StyleBundle("~/css/site").IncludeDirectory("~/public/css", "*.css");
        siteCssBundle.Transforms.Add(new CustomCssMinify());

public class CustomCssMinify : CssMinify
    public override void Process(BundleContext context, BundleResponse response)
        // Workaround for a bug in WebGrease/System.Web.Optimization
        // missing leading whitespace before 'and', 'not', 'only'
        // or Chrome not parsing correctly.
        // hopefully a fix will come!
        base.Process(context, response);
          response.Content = response.Content
            .Replace(")and ", ") and ")
            .Replace(")not ", ") not ")
            .Replace(")only ", ") only ");

Hope that helps someone other than me :)

csharp, chrome, bugs">
comments powered by Disqus