How to remove unused CSS in your Kirby project

I’ve been trying Tachyons on my latest projects and I’m impressed with how fast I can go from idea to a good looking website. If you don’t know what functional CSS is all about, their website explains it well.

But what I’d like to share with you today is relevant if you’re using any CSS framework or library. The problem is that we never use all selectors such frameworks offer and endup pushing lots of unused CSS to the client. How can you check your styles against templates and snippets to make sure you deploy only the CSS that’s actually used? PurifyCSS is a tool that can helps with that problem.

To install it you need Node.js and NPM:

$ npm install --save-dev purify-css

For the purpose of this example we will be using a simple Javascript file to get it working on a Kirby project. Add a purify.js file in the projects root:

// purify.js

const purify = require('purify-css')

const content = ['./site/templates/**/*.php', './site/snippets/**/*.php']
const css = ['./assets/css/main.css']
const options = {
  minify: true,
  output: './assets/css/main.css'

purify(content, css, options)

If you use Grunt, Gulp or Webpack you can check the instruction for those on the project repo.

In the content variable we tell PurifyCSS which Javascript, HTML or PHP files it should look for used CSS selectors. If you use Javascript to manipulate CSS classes or another Kirby plugin that includes any HTML (Patterns, Modules, for example) you must add them to this array as well.

PurifyCSS is the last step in my build process. After concatenated, my main CSS file is placed at assets/css/main.css. Note that we are specifying this file as the input CSS. To purify our CSS we only need to run:

$ node ./purify.js

Or you can add it to the scripts key found on package.json:

"scripts": {
  "purify": "node ./purify.js"

After that will be able to run it with NPM:

$ npm run purify

In my current setup, I’m running PurifyCSS only before deploying my project to production.

After running PurifyCSS the minified CSS went from 84kb to just 35kb (that’s 17kb to 7kb when gzipped).


Awesome, it works perfect, i’ve added the JS files on content const and the css reduction trying on different projects could be 50% less!
Thanks @pedroborges :smiley:

I gave it a try this morning and works very nice. Thank you, it is super useful!