Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

What PostCSS is

PostCSS is a tool that reads CSS, passes it through a chain of plugins and writes the result. On its own it changes nothing: all the work is done by plugins — small JavaScript programs, each solving one task. This course targets PostCSS 8 (version 8.5) and current versions of the plugins.

How it works

PostCSS works in three steps:

  1. The parser turns CSS text into a tree of objects — rules, selectors, properties and values. This tree is called an AST (abstract syntax tree).
  2. Plugins walk the tree one after another and change it: add properties, rewrite values, remove what is not needed.
  3. The stringifier turns the changed tree back into CSS text.

Here is the tree from the inside. You can run this code in Node.js after npm install postcss:

// scripts/ast.js
import postcss from 'postcss';
 
const root = postcss.parse('.post-card { padding: 16px; color: navy; }');
 
root.walkDecls((decl) => {
  console.log(decl.prop, '=', decl.value);
});

node scripts/ast.js prints padding = 16px and color = navy. Plugins work with the same objects: they read decl.prop and decl.value and change them.

What plugins do

PluginJob
AutoprefixerAdds prefixes like -webkit- for the browsers that need them
postcss-preset-envTurns new CSS into a form older browsers understand
postcss-importJoins files included with @import
cssnanoMinifies CSS for production

For example, you write plain CSS for a post card in a blog,

/* styles/main.css */
.post-card {
  padding: 16px;
  user-select: none;
}

and after Autoprefixer you get:

.post-card {
  padding: 16px;
  -webkit-user-select: none;
     -moz-user-select: none;
          user-select: none;
}

The plugin worked out by itself which browsers need prefixes. The Browserslist lesson shows how that is configured.

PostCSS is not a preprocessor

Sass and Less are preprocessors: separate languages with their own variables, mixins and functions that compile to CSS. PostCSS has no language of its own. It takes plain CSS and returns plain CSS, and what it can do depends on the plugins you add. That is why PostCSS often runs after Sass: Sass produces CSS, PostCSS adds prefixes and minifies it.

Where you have already met PostCSS

Many tools use PostCSS inside: Vite processes CSS with it, Stylelint checks styles through its parser, Tailwind CSS was a PostCSS plugin for years. Even if you never installed it yourself, it is probably already in your project's node_modules.

Common mistake

Expecting an installed PostCSS to do something by itself. Without plugins it returns the same CSS it received. If the output has not changed, first check whether plugins are listed in the command or in postcss.config.js.

Thanks for reading!

Donate to the site — we work hard for you.