YUI Compressor and CSS media queries

A few months ago I posted a tip on how to Minimise file size with the YUI Compressor TextMate Bundle. The idea is to get minifying of CSS and JavaScript files into your workflow even if your server or CMS isn’t setup to do it automatically for you.

It works well, but I recently ran into a YUI Compressor bug that had me scratching my head for quite some time. Some of my media queries simply weren’t working. I checked the Media Queries specification, read various tutorials and examples from around the Web, and despite my syntax being correct some things just wouldn’t work. Very frustrating.

Then I started thinking about what could possibly be causing this and had a look inside my minified CSS file. Turns out that YUI Compressor has a bug that affects some media queries. Older versions, unfortunately including the most recent version linked to from the YUI Compressor page, remove the space after the and keyword in media queries.

The following media query:

@media only screen and (max-device-width:480px) {
    body {background:#fcc;}
}

becomes this after minifying:

@media only screen and(max-device-width:480px){body{background:#fcc}}

The space after and is required, so removing it makes the media query malformed and stops all browsers I have tested in from applying the rules within. Media queries that do not contain and, such as @media (max-width:640px;) {} are not affected, which is why some of my media queries worked and others did not.

Luckily this bug has been fixed, but you need to download the latest YUI Compressor from the yui/yuicompressor page at GitHub. Here’s how to install it and make the YUI Compressor TextMate Bundle use the new version (YUI Compressor parts found at Is there a version of YUI Compressor that deals correctly with media queries? on Stack Overflow):

  1. Download YUI Compressor and unzip the archive
  2. Open a Terminal window and move to the unzipped source folder
  3. Type ant and hit return
  4. Move to the build directory the previous step created and run chmod +x yuicompressor-x.x.x.jar to make the file executable (replace ”x.x.x” with the version number of the actual file)
  5. If you want to you can now move the entire YUI Compressor folder to a more suitable place
  6. Switch to TextMate and open the Bundle Editor (Bundles - Bundle Editor - Show Bundle Editor)
  7. Find the YUI Compressor bundle and open the “Preferences…” item
  8. Change the path to point to the new version of YUI Compressor
  9. Close the Bundle Editor

Now try saving a CSS file that contains media queries that use the and keyword. The space after it should now be intact and your media queries work as expected.

Posted on December 20, 2010 in CSS, Coding

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.