• Entelect Staff

Creating flexbox grid using PostCSS

Updated: Aug 14, 2019

As a front-end developer, I continually seek for best-practices when writing CSS and to optimise my workflow. Until now, this was always a challenge but there seems to be light at the end of the tunnel with the introduction of PostCSS. PostCSS is really a game changer and in this article I will show how to create a simple flexbox grid system. If you are not familiar with flexbox, please read the article at CSS-tricks.

Setting up PostCSS with Gulp

First you will need Node installed and initialised. To install PostCSS using Gulp, run the following commands from the terminal:

$ npm i gulp -D
$ npm i gulp-postcss -D
$ npm i gulp-sourcemaps -D
$ npm i gulp-rename -D

In your Gulpfile.js you need to require the following modules:

Make sure you change the path names and extensions to suit your development environment.

Install PostCSS plug-ins

Once you have installed and prepared Gulp, you can install PostCSS plug-ins. For creating a flexbox grid system you will need various powerful plug-ins.To do that, run the following commands from the terminal:

$ npm i postcss-import -D
$ npm i postcss-at-rules-variables -D
$ npm i postcss-each -D
$ npm i postcss-for -D
$ npm i postcss-sassy-mixins -D
$ npm i postcss-custom-properties -D
$ npm i postcss-custom-media -D
$ npm i postcss-media-minmax -D
$ npm i postcss-calc -D
$ npm i postcss-conditionals -D
$ npm i postcss-nested -D
$ npm i autoprefixer -D
$ npm i postcss-browser-reporter -D
$ npm i postcss-reporter -D

Setup Gulp task

Once all plug-ins are installed you can create your Gulp task.

Please be aware of the order of the PostCSS plug-ins.

Folder structure

Before executing gulp, you will need to setup your files in the src folder. Your folder structure should look like this:

 - Gulpfile.js
  - Package.json
  - Src
      - Mixins
         - _grid.scss
      - _grid.scss
      - _vars.scss

PostCSS Mixins directory

To fully make use of all the SASS possibilities, you can use a mixin to demonstrate the power of PostCSS. In your mixin file _grid.scss, add the following mixins:

PostCSS variable file: _vars.scss

You can specify your variables in vars.scss. They become globally available when placing them inside:

:root {
   --example: 1rem;

However, for your grid your variables should be stored outside this scope as you will use a PostCSS plug-in to transform your variables. The following media query variables are needed:

PostCSS grid file: _grid.scss

Finally you can create your PostCSS Bootstrap-like flexbox grid system:

Output file

Run gulp from the command line and the output from a single media query should look like this:


Robert-Jan Kuyper


©2018 by Entelect Software Limited.