7 PostCSS Plugins to Ease You into PostCSS

Share this article

7 PostCSS Plugins to Ease You into PostCSS

We’ve featured PostCSS many times before on SitePoint, yet it continues to confuse many. To summarize it in one sentence:

PostCSS handles tedious jobs so you don’t have to.

It is subtly different to a pre-processor such as Sass, Less and Stylus which provide an alternative, more concise programming language which compiles to CSS. Part of the confusion is caused by:

  • Its name. PostCSS can perform actions on files either before and/or after a pre-processor has compiled its source code to real CSS.

  • PostCSS could replace your pre-processor. There are plugins which implement constructs such as variables, nesting, mixins and extends.

However, while you can build your own pre-processor, there’s little reason to do so unless you want to limit the functionality and increase compilation speed. Personally, I use Sass followed by a sprinkling of PostCSS seasoning to enhance my CSS.

How Do You Use PostCSS?

PostCSS can be used within standalone JavaScript files, Gulp, Grunt, Broccoli, Brunch and a wide range of task runners I’ve never heard of!

On its own, PostCSS does nothing but parse a CSS file into JavaScript objects and tokens. The real magic happens with plugins which examine, manipulate, add or change properties and values before the final CSS file is written.

To use PostCSS in Gulp, you need to set-up your project then install both modules:

npm init
npm install --save-dev gulp gulp-postcss

You can then add the plugins you require, e.g. autoprefixer and cssnano:

npm install --save-dev autoprefixer cssnano

A gulpfile.js can be created. It defines a task which loads the CSS source and pipes it through PostCSS. Plugins and any required options are passed to PostCSS in an array. Finally, the CSS is output to a destination file:

// Gulp.js configuration
var gulp = require('gulp'),
    postcss = require('gulp-postcss');

// apply PostCSS plugins
gulp.task('css', function() {
  return gulp.src('src/main.css')
    .pipe(postcss([
      require('autoprefixer')({}),
      require('cssnano')
    ]))
    .pipe(gulp.dest('dest/main.css'));
});

The task can be run from the console with:

gulp css

All we need now is a handy list of PostCSS plugins…

1. Autoprefixer

If you use nothing else, install Autoprefixer:

npm install --save-dev autoprefixer

Browser-specific prefixes such as -webkit-, -moz- and -ms- are gradually dying out as standards become better supported and vendors opt for alternatives such as flag-based property enabling. Unfortunately, you cannot avoid vendor prefixes but it’s difficult to know when they’re always required, (e.g. for user-select), sometimes required (e.g. for 3D transformations), or never required (e.g. border-radius).

You need never worry about prefixing again with Autoprefixer. You just need to define non-prefixed CSS, then state which browsers you want to support. Autoprefixer will check caniuse.com before adding the necessary prefixes — the following code specifies the last two versions of any mainstream browser, or any exceeding 2% market share:

.pipe(postcss([
  require('autoprefixer')({
    browsers: ['last 2 versions', '> 2%']
  })
]))

This is a superior option to pre-processor library functions which normally require special coding and apply vendor prefixes regardless. Your prefixed code will be removed in future PostCSS runs as browser standards evolve.

Autoprefixer is so useful and widespread, it is possible you’re already using without realizing it is a PostCSS plugin.

2. PostCSS Assets

PostCSS Assets provides a number of useful image-handling functions:

npm install --save-dev postcss-assets

The options include:

  • URL resolution: Given a file name, PostCSS Assets replaces resolve(image) with a root path or fully-qualified URL.
  • Dimension handling: PostCSS Assets replaces references to width(image), height(image) or size(image) with a pixel equivalent.
  • Image inlining: PostCSS Assets replaces inline(image) with a Base64-encoded string.
  • Cache-busting: PostCSS Assets can append a random query string to an image reference to ensure the latest file is loaded.

3. cssnext

cssnext allows you to use the latest CSS syntax today.

npm install --save-dev postcss-cssnext

The plugin has a long list of features including support for:

  • var variables
  • #rrggbbaa colors
  • Color functions
  • Filters
  • Fallbacks

When it executes, cssnext translates code to a syntax commonly supported in today’s browsers.

4. Rucksack

Rucksack offers a range of functions which, the developer claims, makes CSS development fun again!

npm install --save-dev rucksack-css

Options include:

  • Responsive typography which adjusts font sizes and line heights with a single font-size: responsive declaration.
  • Quantity pseudo-selectors such as li:at-least(4) which targets any list with four or more items.
  • Property aliases such as defining bg as background which can be used throughout your CSS.
  • A set of pre-defined easing functions.

5. Stylelint

Stylelint reports CSS errors based on 140 rules designed to catch common mistakes, implement style conventions and enforce best practices. There are many options to configure Stylelint to your liking — Pavels Jelisejevs’ article Improving the Quality of Your CSS with PostCSS walks you through the set up process.

6. CSS MQPacker

MQPacker optimizes your media queries into single rules when possible:

npm install --save-dev css-mqpacker

Pre-processors such as Sass make it easy to use media queries within a declaration, e.g.

.widget1 {
  width: 100%;

  @media (min-width: 30em) {
    width: 50%;
  }

  @media (min-width: 60em) {
    width: 25%;
  }
}

.widget2 {
  width: 100px;

  @media (min-width: 30em) {
    width: 200px;
  }
}

This compiles to:

.widget1 { width: 100%; }

@media (min-width: 30em) {
  .widget1 { width: 50%; }
}

@media (min-width: 60em) {
  .widget1 { width: 25%; }
}

.widget2 { width: 100px; }

@media (min-width: 30em) {
  .widget2 { width: 200px; }
}

To reduce file sizes and (possibly) improve parsing times, MQPacker packs multiple declarations into one @media rule, i.e.

.widget1 { width: 100%; }
.widget2 { width: 100px; }

@media (min-width: 30em) {
  .widget1 { width: 50%; }
  .widget2 { width: 200px; }
}

@media (min-width: 60em) {
  .widget1 { width: 25%; }
}

Hot tip: ensure the first media query declaration in your code defines all possible options in the order you want them even if there’s no actual difference. This guarantees MQPacker will define rules in the correct order.

MQPacker also provides options for sorting media queries and outputting source maps.

7. cssnano

cssnano compacts your CSS file to ensure the download is as small as possible in your production environment. Install it via:

npm install --save-dev cssnano

The plugin works by removing comments, whitespace, duplicate rules, outdated vendor prefixes and making other optimizations to typically save at least 50%. There are alternative options but cssnano is one of the best. Use it!

Want More?

A searchable index of PostCSS plugins is available at postcss.parts and the PostCSS usage documentation provides a list of recommended options. You’ll find plugins for almost any CSS task you can imagine although be aware there is some cross-over and duplication — for example, cssnext also includes Autoprefixer.

If that’s not enough, you can develop your own PostCSS plugins in JavaScript. The PostCSS documentation explains how to write a plugin and provides an API reference.

PostCSS makes CSS development easier regardless of whether you use a pre-processor. The CSS development time it saves more than outweighs the initial installation and configuration effort.

Frequently Asked Questions about PostCSS Plugins

What are the benefits of using PostCSS plugins?

PostCSS plugins offer a range of benefits to developers. They allow for a more efficient and streamlined coding process, as they can automate repetitive tasks, reduce errors, and enhance the functionality of your CSS. They also offer a high level of customization, as you can choose from a wide range of plugins to suit your specific needs. Additionally, PostCSS plugins are generally easy to install and use, making them accessible to developers of all skill levels.

How do I install PostCSS plugins?

Installing PostCSS plugins is a straightforward process. First, you need to install PostCSS itself, which can be done using npm (Node Package Manager). Once PostCSS is installed, you can install individual plugins using npm as well. Each plugin will have its own specific installation instructions, which can usually be found on the plugin’s GitHub page or official documentation.

Can I use multiple PostCSS plugins at once?

Yes, you can use multiple PostCSS plugins at once. In fact, one of the main advantages of PostCSS is its modular nature, which allows you to pick and choose the plugins that best suit your needs. You can combine different plugins to create a custom CSS processing pipeline. However, it’s important to be aware of potential conflicts between plugins and to ensure that they are configured correctly.

How do I choose the right PostCSS plugins for my project?

Choosing the right PostCSS plugins for your project depends on your specific needs and objectives. You should consider factors such as the complexity of your project, the features you need, and your personal coding style. It can be helpful to research different plugins, read reviews and documentation, and experiment with different options to find the best fit.

Are there any downsides to using PostCSS plugins?

While PostCSS plugins offer many benefits, there can be potential downsides. For example, using too many plugins can slow down your build process, and some plugins may not be maintained or updated regularly. It’s also important to be aware that while PostCSS plugins can enhance your CSS, they can’t replace a solid understanding of CSS fundamentals.

How do I update PostCSS plugins?

Updating PostCSS plugins is typically done through npm. You can check for updates using the ‘npm outdated’ command, and then update individual plugins using the ‘npm update’ command followed by the plugin name. It’s important to keep your plugins updated to benefit from bug fixes, new features, and performance improvements.

Can I create my own PostCSS plugins?

Yes, you can create your own PostCSS plugins if you have the necessary JavaScript knowledge. Creating your own plugins allows you to tailor the functionality of PostCSS to your specific needs. There are resources and tutorials available online that can guide you through the process of creating a PostCSS plugin.

How do I troubleshoot issues with PostCSS plugins?

Troubleshooting issues with PostCSS plugins can involve several steps. First, ensure that the plugin is installed and configured correctly. Check the plugin’s documentation for any known issues or solutions. If the issue persists, you can try reaching out to the plugin’s developer or the PostCSS community for help.

What are some popular PostCSS plugins?

There are many popular PostCSS plugins available, each with its own unique features. Some popular choices include Autoprefixer, which automatically adds vendor prefixes to your CSS; cssnano, which minifies your CSS for production; and postcss-preset-env, which allows you to use future CSS features today.

How do I uninstall PostCSS plugins?

Uninstalling PostCSS plugins is done through npm. You can uninstall a plugin using the ‘npm uninstall’ command followed by the plugin name. It’s important to remove any references to the plugin in your code or configuration files to avoid errors.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

AdvancedCSSCSSGruntGulpLESSpatrickcpost-processorPostCSSpre-processorsassStylus
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week