# PostCSS Deep Dive: Preprocessing with “PreCSS”

This post is part of a series called PostCSS Deep Dive.
Using PostCSS for Minification and Optimization
PostCSS Deep Dive: Roll Your Own Preprocessor

In the last two tutorials we looked at ways to use PreCSS on completed stylesheets to enhance their cross browser compatibility and optimization, essentially as a post-processor. In this tutorial you’ll learn to use PostCSS as a pre-processor, in the same way you would use Stylus, Sass or LESS.

There are two main ways you can go about using PostCSS for preprocessing. One is to select all your own plugins to add the preprocessor functionality you want, and the other is to install a pack of preselected plugins so you’re ready to go right away.

We’ll start with the quickest and easiest approach, installing the excellent PreCSS pack of plugins, created by Jonathan Neal. In the tutorial after this we’ll move onto how you can put together your own preprocessor, using only the functionality you want.

This tutorial will assume you have some degree of familiarity with the features commonly found in preprocessors like Stylus, Sass or LESS. That’s purely because we’ll be focusing on how you can use these same types of features via PostCSS, rather than what the features actually do. That said though, even if you’ve never used a preprocessor before, this might be the perfect place to start.

## Try Out PreCSS Live

We’ll go through how to setup a Gulp or Grunt project using PreCSS in the next section, however, if you would like to take a shortcut, (just for now), you can alternatively use the live demo playground to try out the code we’ll run through in this tutorial. Code can be typed into the left window, and it will automatically compile for you and display in the right window.

The first thing you’ll need to do is setup your project to use either Gulp or Grunt, depending on your preference. If you don’t already have a preference for one or the other I recommend using Gulp as you’ll need less code to achieve the same ends.

You can read about how to setup Gulp or Grunt projects for PostCSS in the previous tutorials

respectively.

If you don't want to manually setup your project from scratch though, you can download the source files attached to this tutorial, and extract either the provided Gulp or Grunt starter project into an empty project folder.

Then, with a terminal or command prompt pointed at the folder, run the commandnpm install.

### Install PreCSS

Whether you’re using Gulp or Grunt, install PreCSS into your project with the command:

 1 npm install precss --save-dev 

### Load as a Gulp Plugin

If you’re using Gulp, add this variable under the variables already in the file:

 1 var precss = require('precss'); 

Now add the new variable name into your processors array:

 1  var processors = [  2  precss  3  ]; 

Do a quick test that everything is working by running the command gulp css then checking that a new “style.css” file has appeared in your project’s “dest” folder.

### Load as a Grunt Plugin

If you’re using Grunt, update the processors object, which is nested under the options object, to the following:

 1  processors: [  2  require('precss')()  3  ] 

Do a quick test that everything is working by running the command grunt postcss then checking that a new “style.css” file has appeared in your project’s “dest” folder.

You now have everything you need to use PreCSS installed and ready to go. This means we’re ready to start stepping through the some of the preprocessing capabilities of PreCSS and how they can be used.

## Preprocessing via “PreCSS”

Generally speaking, PreCSS syntax is most similar to that of Sass. However it does use some of its own unique approaches, which we’ll cover as we go along.

Note: because of the Sass-like syntax of PreCSS, you’ll find that a Sass syntax highlighter will work best for you in your favorite text editor.

### Nesting

Nesting is something common to all three of the major preprocessors, i.e. Stylus, Sass and LESS, and it’s also present in PreCSS. Nesting in PreCSS is done in the same way as in Sass and LESS, by placing selectors inside the curly brackets of other selectors.

The ability to use the & symbol to have the parent selector duplicated into the child selector also works in the same way in PreCSS as in other preprocessors.

 1 .menu {  2  width: 100%;  3  a {  4  text-decoration: none;  5  }  6  &::before {  7  content: '';  8  }  9 } 

Compile your CSS with gulp css or grunt postcss and your “dest/style.css” file should have evaluated the nested code into the following:

 1 .menu {  2  width: 100%;  3 }  4 5 .menu a {  6  text-decoration: none;  7 }  8 9 .menu::before {  10  content: '';  11 } 

### Variables

Variables are another type of functionality common to all preprocessors, and they are included in PreCSS. The only thing typically differing between each preprocessor is the syntax to denote variables.

• LESS variables begin with an @ symbol and place a : before the value.
• Stylus variables can optionally use a $ symbol and place an = sign before the value. • Sass variables use a $ symbol and place a : before the value.

In keeping with the PreCSS tendency to uses Sass like syntax, it too places a $ before the variable name and a : before the value. Try out using PreCSS variables by adding this to your “src/style.css” file:  1 $text_color: #232323;  2 3 body {  4  color: $text_color;  5 }  After recompiling you should see this resulting code:  1 body {  2  color: #232323;  3 }  ### Conditionals Conditionals, i.e. if and else logic, are a feature that is very strong in both Sass and Stylus. LESS offers guarded mixins, but they don’t offer quite the same degree of power. Conditionals are present in PreCSS and follow the same syntax as Sass, using @if and @else Add this example code to your “src/style.css” file:  1 $column_layout: 2;  2 3 .column {  4  @if $column_layout == 2 {  5  width: 50%;  6  float: left;  7  } @else {  8  width: 100%;  9  }  10 }  In the above example we’re having a .column class output differently depending on if we want a one column layout, or a two column layout. We have the $column_layout variable set to 2, meaning we should see width: 50%; float: left; output into our class.

Compile your file, and you should see the following in your “dest/style.css” file.

 1 .column {  2  width: 50%;  3  float: left  4 } 

Note: the postcss-advanced-variables plugin that provides this conditionals functionality is still quite new, and I have encountered some unexpected output when using it for more complex conditionals, however, I’m sure it will be updated in the near future.

There is an alternative plugin that can be used for conditionals named postcss-conditionals. We’ll cover how you can use that plugin (if you choose) in the next tutorial, “Rolling Your Own Preprocessor”.

### Loops - @for and @each

There are two types of loops available in PreCSS, the @for and @each loops. Both of these use an approach that is just like Sass. “For” loops let you cycle through a numerical counter, while “each” loops let you cycle through a list of items.

#### @for Loops

In a @for loop there is a “counter” variable that keeps track of where you are in cycling through your numeric counter, typically set as $i. For example, when iterating from 1 to 3 there will be three loops; in the first $i will equal 1, the second it will equal 2 and the third it will equal 3

This $i counter variable can be interpolated into both selectors and rules, which can be very handy for things like generating nth-of-type() rules and calculating widths. Add this code to your “src/style.css” file to try out a @for loop:  1 @for$i from 1 to 3 {  2  p:nth-of-type($i) {  3  margin-left: calc( 100% /$i );  4  }  5 } 

After compilation you should see this code expanded out to:

 1 p:nth-of-type(1) {  2  margin-left: calc( 100% / 1 );  3 }  4 5 p:nth-of-type(2) {  6  margin-left: calc( 100% / 2 );  7 }  8 9 p:nth-of-type(3) {  10  margin-left: calc( 100% / 3 );  11 } 

Note: numbers 1, 2 and 3 have been inserted into each of the above styles.

#### @each Loops

An @each loop cycles through a list of items instead of numbers. As with @for loops, the variable representing the loop’s current item can be interpolated into selectors and rules. Note that to interpolate into a string, you need to insert a set of brackets into the variable name in the format $(var) Give using PreCSS @each loops a go by adding the following example code:  1 $social: twitter, facebook, youtube;  2 3 @each $icon in ($social){  4  .icon-$(icon) {  5  background: url('img/$(icon).png');  6  }  7 } 

After compilation you should see the following CSS has been generated:

 1 .icon-twitter {  2  background: url('img/twitter.png');  3 }  4 5 .icon-facebook {  6  background: url('img/facebook.png');  7 }  8 9 .icon-youtube {  10  background: url('img/youtube.png');  11 } 

### Mixins

The syntax for mixin creation is one aspect of PreCSS that’s a little different to Sass.

In Sass, to define a mixin you use the syntax @mixin mixin_name($arg1,$arg2) {...} and then use it with @include mixin_name(pass_arg1, pass_arg2);.

In PreCSS, on the other hand, you define a mixin with the syntax @define-mixin mixin_name $arg1,$arg2 {...} and use it with @mixin mixin_name pass_arg1, pass_arg2;

 1 @define-mixin icon $network,$color {  2  .button.$(network) {  3  background-image: url('img/$(network).png');  4  background-color: $color;  5  }  6 }  7 8 @mixin icon twitter, blue;  9 10 @mixin icon youtube, red;  On compilation you should see:  1 .button.twitter {  2  background-image: url('img/twitter.png');  3  background-color: blue;  4 }  5 6 .button.youtube {  7  background-image: url('img/youtube.png');  8  background-color: red;  9 }  Note: arguments passed through the mixin can be interpolated into selectors and strings with the same approach as mentioned in @each loops above; with the format $(var).

#### Using @mixin-content

As well as using mixins in the way shown above, they can also be set to consume blocks of content passed when calling the mixin. This is essentially the same process as with Sass’ @content

For instance, modify the mixin from the above example, placing @mixin-content where you want a passed block of content to appear, like so:

 1 @define-mixin icon $network,$color {  2  .button.$(network) {  3  background-image: url('img/$(network).png');  4  background-color: $color;  5  @mixin-content;  6  }  7 }  When a mixin incorporating @mixin-content is used, it must be placed with curly brackets, rather than on a single line ending with a ;, or it will fail to compile. Update your code so your mixin calls look like this:  1 @mixin icon twitter, blue {  2  width: 3rem;  3 }  4 5 @mixin icon youtube, red {  6  width: 4rem;  7 }  After compilation, this should yield the following code - notice the inclusion of the width content passed through each use of the mixin:  1 .button.twitter {  2  background-image: url('img/twitter.png');  3  background-color: blue;  4  width: 3rem;  5 }  6 7 .button.youtube {  8  background-image: url('img/youtube.png');  9  background-color: red;  10  width: 4rem;  11 }  ### Extends Extends are similar to mixins in a sense, in that they’re designed to allow you to reuse blocks of code. However, the idea behind “extends” is to create a base set of code you know you’re going to use in the exact same way multiple times for a certain type of element. You can then subsequently extend on that base with additional, non-default code. In PreCSS, the syntax to define an extend is @define-extend extend_name {...}. In your “src/style.css” file, define an extend containing the base styles for a rounded button like so:  1 @define-extend rounded_button {  2  border-radius: 0.5rem;  3  padding: 1em;  4  border-width: 0.0625rem;  5  border-style: solid;  6 }  This default set of styles is now ready be extended on with extra code, for example, setting things like background-color and border-color. This is done by using the syntax @extend extend_name; to import the base styles defined in the extend. Add this example code, underneath the code you just added:  1 .blue_button {  2  @extend rounded_button;  3  border-color: #2F74D1;  4  background-color: #3B8EFF;  5 }  6 7 .red_button {  8  @extend rounded_button;  9  border-color: #C41A1E;  10  background-color: #FF2025;  11 }  Where the @extend rounded_button; line is used, the entire contents of the extend will be inserted. Compile your styles and you should get:  1 .blue_button,  2 .red_button {  3  border-radius: 0.5rem;  4  padding: 1em;  5  border-width: 0.0625rem;  6  border-style: solid;  7 }  8 9 .blue_button {  10  border-color: #2F74D1;  11  background-color: #3B8EFF;  12 }  13 14 .red_button {  15  border-color: #C41A1E;  16  background-color: #FF2025;  17 }  Note also that the styles common to the .blue_button and .red_button class have been combined for efficiency. ### Imports The plugin used for inlining stylesheets via @import is the same one we covered in the previous tutorial of this series: For Minification and Optimization. For a rundown on how it works head over and have a read of the sectioned headed “Inline / Combine Files with @import”. In the context of using PostCSS as a preprocessor, imports become even more useful as they give you the option of setting up partials, something you might be used to from other preprocessing solutions. For example, you might setup a “partials” folder, separate your project into logically discrete partial files then import them like so:  1 @import "partials/_variables.css";  2 @import "partials/_utilities.css";  3 @import "partials/_mixins.css";  4 @import "partials/_extends.css";  ## Let’s Recap I hope you now have some insights into how powerful PostCSS can be as a preprocessor by way of the PreCSS pack. To summarize what we covered above: • You can try out PreCSS live at https://jonathantneal.github.io/precss. • Nesting in PreCSS works the same way as Sass and LESS. • Variables in PreCSS use the same syntax as Sass. • Conditionals are present in PreCSS, using the syntax @if and @else. • @for and @each loops are available. • PreCSS mixins are defined with the syntax: @define-mixin mixin_name$arg1, \$arg2 {...}
• PreCSS mixins are used with the syntax:
@mixin mixin_name pass_arg1, pass_arg2;
• @mixin-content can be used in the same way as Sass' @content
• Extends in PreCSS are defined with the syntax:
@define-extend extend_name {...}
• Extends are used with the syntax:
@extend extend_name;
• @import inlines external CSS files, particularly helpful for using partials

## In the Next Tutorial

PreCSS is a fantastic project, bringing together some excellent language extension plugins and making PostCSS-based preprocessing pretty much plug and play. It provides almost all of the functionality most preprocessor users have come to expect, and is a quick, “no fuss” way to get the PostCSS preprocessor ball rolling.

Using PreCSS is one of the two methods of PostCSS preprocessing we mentioned at the start of this tutorial. The other method is to setup your own preprocessor, hand picking the language extension plugins that suit your own projects or coding style. The trade off is it’s a little more setup, but in return you get the freedom to put together a preprocessor that works however you want it to.

You’ll learn how to do this in the next tutorial, “Roll Your Own Preprocessor”.