DEV Community

Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

Getting started with PostCSS in 2019

If you’ve ever wanted to try out new, experimental, or nonstandard CSS properties in your code, then you know browser vendors require you to add prefixes to make them work until they are fully standardized.

.some-element {
 box-sizing: border-box;
 -webkit-box-sizing: border-box;  // chrome, safari prefix
 -moz-box-sizing: border-box;     // firefox
 -o-box-sizing: border-box;       // old opera versions
 -ms-box-sizing: border-box;      // IE, Microsoft Edge
}

You have to monitor the different CSS properties to know when browser vendors begin supporting them, at which point you can remove the respective prefixes.

Thankfully, now we have Autoprefixer. It’s a CLI tool from npm that scans through your code and adds vendor prefixes to CSS rules using values from Can I Use. Autoprefixer is one of the many PostCSS plugins, and it captures the essence of PostCSS.

What is PostCSS, really?

PostCSS is a tool for transforming CSS with JavaScript plugins. It provides features via its extensive plugin ecosystem to help improve your CSS writing experience. You can pick the plugins you need or even write a custom one for yourself.

Generally, PostCSS plugins allow you to write plain CSS as you normally would, and once invoked, they scan through the code to perform the desired transformations.

Do note, however, that there are PostCSS plugins that do not transform plain CSS, but operate on Sass-like syntax. One example is the PostCSS Simple Variables plugin, which allows you to implement variables (just like in Sass) that you can reuse throughout your code, as shown below.

$color-brand: darkgrey;
$font-size: 1em;
body {
 color: $color-brand;
 font-size: $font-size;
}

This feature isn’t especially relevant at this time because /CSS variables/ has been released as an inherent feature in CSS, and PostCSS can transform the latest CSSNext syntax into friendly CSS that older browsers can understand.

Why use PostCSS?

Let’s take a look at a few use cases for PostCSS via the power of its plugins.

Autoprefixing

As previously mentioned, the Autoprefixer plugin will add vendor prefixes to CSS properties using values from Can I Use. This reduces clutter in your code and improves readability. For example, this input:

:fullscreen {
}

Gives this output:

:-webkit-:full-screen {}
:-moz-:full-screen {}
:full-screen {}

Using CSSNext features that browsers understand

With the PostCSS Preset Env plugin, you can write future CSS syntax, and the plugin will convert it to CSS that browsers will understand by working out the necessary polyfill. For example, this input:

@custom-media --med (width <= 50rem);
@media (--med) {
  a { 
    &:hover {
      color: color-mod(black alpha(54%));
    }
  }
}

Gives this output:

@media (max-width: 50rem) {
  a:hover  { 
    color: rgba(0, 0, 0, 0.54);
  }
}

Avoiding errors in your CSS

The stylelint plugin points out errors in your CSS code. It supports the latest CSS syntax. For example, this input:

a { 
  color: #d3;
}

Gives this output:

app.css
2:10 Invalid hex color

Using locally scoped CSS class names

With the CSS Modules plugin, you can write CSS that is locally scoped to components, meaning there won’t be any conflicts between your CSS class names no matter how generic they are. For example, this input:

.name {
  color: grey;
}

Gives this output:

.Logo__name__SVK0g {
  color: gray;
}

Creating stunning grids

The LostGrid plugin uses calc() to create grids based on fractions you define without the need to pass a lot of options. For example, this input:

div {
  lost-column: 1/3 
}

Gives this output:

div {
  width: calc(99.9% * 1/3 -  
  (30px - 30px * 1/3)); 
}
div:nth-child(1n) {
  float: left; 
  margin-right: 30px; 
  clear: none; 
}
div:last-child {
  margin-right: 0; 
}
div:nth-child(3n) {
  margin-right: 0; 
  float: right; 
}
div:nth-child(3n + 1) {
  clear: both; 
}

The difference between PostCSS, Sass, and Less

PostCSS can do the same work as preprocessors like Sass, Less, and Stylus, but PostCSS is modular and, in my experience, faster.

The main difference between PostCSS and CSS preprocessors is that you can pick the features you need. Sass and Less give you lots of features you may or may not use, and which you can’t extend.

If you want to keep Sass, Less, or Stylus in your current stack but still want to get PostCSS to perform other functions Sass can’t (e.g., autoprefixing or linting), this article details how to do just that.

There are also PostCSS plugins like PostCSS Sass and PreCSS, which are essentially complete replacements for Sass. This means you could literally write your own preprocessor powered by PostCSS.

Quick PostCSS setup using Codepen

Start by signing in to Codepen.io, and perform the following steps:

  1. Create a new pen.
  2. Click Settings at the top of the window to reveal a settings panel.

  1. Select CSS from the top tab to reveal CSS settings.

  1. Select the CSS Processor dropdown, then choose PostCSS from the dropdown.

  1. Click on the Need an add-on? badge that shows up. A list of add-ons will be displayed, from which you can search and select a needed plugin. Let’s Add the postcss-simple-vars plugin to experiment with variables. Select Save & Close.

Back on the CSS window, you will notice that the plugin has been referenced for use. We are now free to access all its features.

@use postcss-simple-vars;

Insert a sample HTML and CSS using variables in the CSS window:

Demo

Other setup methods

There are several ways to set up PostCSS with build tools such as Gulp, Webpack, or Parcel. In this post, I will focus on using the PostCSS CLI.

PostCSS CLI

With npm installed, run the following on your command line:

npm install -g postcss-cli

Or use yarn :

yarn global add postcss-cli

You can also add plugins to projects using npm. For example:

yarn add --dev autoprefixer postcss-nested postcss-cli

In our projects, we can generally transform CSS with a PostCSS plugin this way:

postcss --use autoprefixer -o main.css css/*.css

The above command will run Autoprefixer through all the files contained in the /css/ folder and output the transformed CSS into main.css. You can also use an alias to run commands by adding it to scripts in your package.json file:

{
...
"scripts": {
 "start": "node index.js",
 "postcss": "postcss --use autoprefixer -o main.css css/*.css"
  }
...
}

Create React App and Vue

It is worth mentioning that scaffolded React and Vue projects such as Create React App and VueCLI use PostCSS internally. Also note that the internal PostCSS is set up with a few select plugins; you can add more plugins with more configuration.

Conclusion

PostCSS is a highly useful tool that has been around for a while now. It encourages you to write more of plain CSS and allows you to use or write your own powerful plugins to transform it. Learning this tool, or at least becoming more aware of its uses, will improve your front-end workflow in 2019.

If you would like to dive deeper into PostCSS, I highly recommend this tutorial series. Thanks for reading 🙏.


Plug: LogRocket, a DVR for web apps

https://logrocket.com/signup/

LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

Try it for free.


The post Getting started with PostCSS in 2019 appeared first on LogRocket Blog.

Top comments (0)