Minify CSS

PageSpeed Service was turned off on August 3rd, 2015. Please see Turndown Information for PageSpeed Service.

Objective

Reduce payload size for both external and inline CSS.

PageSpeed rule

This rewriter implements the PageSpeed rule for minimizing payload size.

Description

This filter parses linked and inline CSS, rewrites the images found and minifies the CSS. The filter works on CSS found in <style> blocks and <link> refs.

Many images are referenced from CSS rather than HTML. If OptimizeImages or ProxyImages are enabled this filter finds and rewrites those images, saving bytes and extending cache lifetimes.

Minification can drastically reduce the byte count in common CSS by stripping all comments and most whitespace and shortening color names. This filter can be used to avoid the extra step of minifying CSS by hand when constructing and maintaining a site.

Only URLs of resources with public or no Cache-Control headers are optimized.

Operation

This rewriter parses the HTML document and finds all CSS referenced in <link> tags and inline in <style> tags. It parses that CSS, optimizes or proxies all images found in url() values and minifies the result.

Example

For example, if the HTML document looks like this:

<html>
  <head>
    <style>
      body { background-image: url("foo.png"); }
      /* This comment will be stripped */
      #iddy, .anotherId {
        border: solid 1px #cccccc;
        padding: 1.2em;
        float: left;
        color:##ff0000;
      }
    </style>
    <link rel="stylesheet" type="text/css" href="extStyle.css">
  </head>
  <body>
    Wow, <div class="classy" id="iddy">
    CSS is <span>stylin'</span>.</div>
  </body>
</html>

With the following in extStyle.css:

  div.classy span, div.classy img {
    display: block;
    border: none !important;
    background: none !important;
  }

Then it will be rewritten into:

<html>
  <head>
    <style>body{background-image:url(http://1-ps.googleusercontent.com/h/www.example.com/dir/xfoo.png.pagespeed.ic.HASH.png}#iddy,#anotherId{border:solid 1px #ccc;padding:1.2em;float:left;color:red}</style>
    <link rel="stylesheet" type="text/css" href="http://1-ps.googleusercontent.com/h/www.example.com/dir/I.extStyle.css.pagespeed.cf.HASH.css">
  </head>
  <body>
    Wow, <div class="classy" id="iddy">
    CSS is <span>stylin'</span>.</div>
  </body>
</html>

And the rewritten file I.extStyle.css.pagespeed.cf.HASH.css will contain:

  dif.classy span,div.classy img{display:block;border:none!important;background:none!important}

Limitations

Not all CSS3 or proprietary constructs are parsed. When unhandled syntax is present and the file cannot be parsed completely, the CSS file is left unmodified.