Using Ant to decouple mobile first CSS from Media Queries

Often you want to progressively enhance your mobile-first websites, making them responsive, but that obviously requires a fallback plan for legacy IE browsers that don’t support CSS3 Media Queries. You also want to manage the deployment process and follow the DRY principle as much as you can. You could of course use a polyfill but that means introducing a JavaScript dependancy for layout which might not be what you want. Luckily, there are other solutions.

Nicolas Gallagher recently posted a brilliant article, Mobile first CSS and getting Sass to help with legacy IE, in which he suggests using a pre-processor to produce two versions of compiled CSS from the same core code. He is basically extending Jeremy Keith’s Windows mobile media queries method.

Using Ant as pre-processor

Inspired by Nicolas’ article, I’ve adapted the Ant build script that I use in my One Web Boilerplate, to do the same kind of file pre-processing on the server side when doing a build. This enables you to work on the same stylesheets when developing, and then generate two versions, to serve legacy IE browsers a desktop layout, while more capable browser get the enhanced version with Media Queries.

Ant ReplaceRegExp task

Before minifying the files, the script inlines all @import-ed styles and then turns Media Queries into comments wherever it sees /*replace*/, like so:


/*replace*/@media only screen and (min-width: 30em) {/*replace*/
/*Styles*/
}/*replace*/

For IE-specific stylesheet, this is changed like below and then minified:


/*@media only screen and (min-width: 30em) {*/
/*Styles*/
/*}*/

Modern browsers get the minified version with Media Queries in place.

I could have of course used Sass, but since my framework already uses Ant, and since I want to keep it generic, I didn’t want to add any other external dependencies to it. Also, I’ve written earlier about how Apache Ant can help you building and optimizing frontend code so I know how incredibly useful Ant can be for code deployment.

See it on GitHub

See the One Web Boilerplate README on GitHub for info on how it works! Decoupling your layout CSS rules from the actual Media Queries during build time can greatly improve your workflow and help managing your code.