Autoprefixing

Kea - High level abstraction between React and Redux - Interview with Marius Andra

It can be difficult to remember which vendor prefixes you have to use for specific CSS rules to support a large variety of users. Autoprefixing solves this problem. It can be enabled through PostCSS and the autoprefixer plugin. autoprefixer uses Can I Use service to figure out which rules should be prefixed and its behavior can be tuned further.

Setting Up Autoprefixing#

Achieving autoprefixing takes a small addition to the current setup. Install postcss-loader and autoprefixer first:

npm install postcss-loader autoprefixer --save-dev

Add a fragment enabling autoprefixing:

webpack.parts.js

exports.autoprefix = () => ({
  loader: 'postcss-loader',
  options: {
    plugins: () => ([
      require('autoprefixer')(),
    ]),
  },
});

To connect the loader with ExtractTextPlugin, hook it up as follows:

webpack.config.js

const productionConfig = merge([
parts.extractCSS({ use: 'css-loader' }),
parts.extractCSS({ use: ['css-loader', parts.autoprefix()], }),
]);

To confirm that the setup works, there should be something to autoprefix. Adjust the CSS:

app/main.css

body {
  background: cornsilk;
display: flex;
}

If you build the application now (npm run build) and examine the built CSS, you should be able to find a declaration there:

body {
  background: cornsilk;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

As you can see, autoprefixing expands the rules. If you know what browsers you support, it's possible to set up a .browserslistrc file. Different tools pick up this definition, autoprefixer included.

Consider the example below where you select only specific browsers:

.browserslistrc

> 1% # Browser usage over 1%
Last 2 versions # Or last two versions
IE 8 # Or IE 8

Conclusion#

Autoprefixing is a convenient technique as it decreases the amount of work needed while crafting CSS. You can maintain minimum browser requirements within a .browserslistrc file. The tooling can then use that information to generate optimal output.

To recap:

  • Autoprefixing can be enabled through the autoprefixer PostCSS plugin.
  • Autoprefixing writes missing CSS definitions based on your minimum browser definition.
  • .browserslistrc is a standard file that works with tooling beyond autoprefixer

In the next chapter, you'll learn to eliminate unused CSS from the project.

Previous chapterSeparating CSS

This book is available through Leanpub (digital), Amazon (paperback), and Kindle (digital). By purchasing the book you support the development of further content. A part of profit (~30%) goes to Tobias Koppers, the author of webpack.

Need help?