Greg Babiars's Blog

Write Prefix-free CSS using Grunt

July 21, 2013

One of the most painful parts about using newer CSS3 features is the amount of prefixed styles that must be written in order to support the wide range of browsers out there. There are many ways to alleviate this pain, including preprocessor mixins. One of the best ways I’ve found to eliminate this altogether is to have the prefix generation automated into your build process. By moving prefixing to this automation step, we can write more maintainable css that will also be easier to update with future browser changes.

Automating using Grunt

My build tool of choice is Grunt, particularly because of the large number of task plugins available. One such plugin is available for automating prefix generation of css, called grunt-autoprefixer. To make use of it, we simply need to point to the files we want to generate and the prefixed css will be generated.

Our Grunt snippet:

autoprefixer: {
  options: {
    browsers: ['last 2 versions']
  },
  dist: {
    files: {
      'css/dist/styles.css': ['css/src/styles.css']
    }
  }
}

Example of css with flexbox:

.column {
  display: flex;
}

The resulting css generated by autoprefixer:

.column {
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
}

As you can see, the css we write is much simpler than the generated css and we no longer have to worry ourselves with maintaining prefixes as browser support changes. Updating our css is as simple as rerunning our Grunt task.

You can modify which browsers are supported by changing the browser array in the grunt-autoprefixer options. For more documentation, check out the github repo.


Greg BabiarsWritten by Greg Babiars who builds things for the web. You can follow me on Twitter.