lyncd

Some minor improvements to Minify for CSS

Recently I was taking a closer look at some minified CSS output, and I noticed a few things that Minify could be doing to compress CSS slightly better.

Here’s a single line of CSS that demonstrates the compression issues I’ve found:

// Before: 53 bytes
p, .alert a { margin: -0.5em 0.5em; padding: .5em; }

// After Minify: 47 bytes
p, .alert a{margin: -0.5em 0.5em;padding: .5em}

// "Complete" compression: 42 bytes
p,.alert a{margin:-.5em .5em;padding:.5em}

Wow, five whole bytes in just one line! Briefly, what Minify misses are:

Leading zeroes before decimals
I’ve checked the spec on these, and they’re unnecessary. (See: “A <number> can either be an <integer>, or it can be zero or more digits followed by a dot (.) followed by one or more digits.”)
Leading space before a dash or decimal
It’s safe to remove the spaces in “margin: -0.5em” and “padding: .5em.”
Spaces after commas
Minify tries to remove these, but a class name with a descendant selector is enough to trip it up, as in “p, .alert a { … }.”

The code

Although I use it, this code snippet isn’t complete or production-ready: A big limitation is that it doesn’t escape quoted strings. It’s just a proof-of-concept Band-Aid layer to gather feedback and see whether it’s worth submitting a “real” patch to Minify.

So, please try this on your own CSS, but be sure to diff against a regular minified version to double-check the changes it makes.

# Run Minify_CSS::minify on $css FIRST, then:
$css = preg_replace('/([:\s]-?)0(?=\.)/', '\1', $css); # zap leading zeroes
$css = preg_replace('/:\s(?=\.|-)/', ':', $css); # zap leading spaces
$css = str_replace(', ', ',', $css); # zap spaces after commas

If you can think of any problems with what I’m doing, or know about a browser I’m breaking compatibility with, I’d love to here from you!

Filed under: Code.  Tagged: , .

3 comments »

  • […] Here’s a single line of CSS that demonstrates the compression issues I’ve found: //… [full post] sticks lyncd codecssminify 0 0 0 0 0 [03 Dec […]

  • FWIW, for Minify I’ve decided it best to port YUI Compressor’s CSS minifier to PHP (soonish), which will probably cover your fixes. YUI’s algorithm was too limited at first, but they’ve since added better hack handling and have surpassed my compression ratios.