I’ve been using Tailwind CSS a lot recently. I wasn’t an early adopter, but after using it in earnest on a couple projects I’ve come to appreciate its simplicity. Once I internalized the nomenclature of its utility classes and embraced the constraints, my productivity soared. And designing custom web UIs became fun again. Indeed, I’m looking forward to using Tailwind on a few more projects I’ve got teed up.

This tutorial walks through how I add Tailwind CSS to my Phoenix projects. But more than that, I hope this tutorial helps you better understand how everything gets knitted together using webpack and PostCSS. The first time I tried this, I cargo-culted some configuration and cobbled it together without knowing why it worked. It’s easy to rationalize. I figured I’d need to become a webpack expert to go any deeper. Turns out you can learn a lot by just going one level below the surface.

So, before we dive into the details, let’s start by understanding the roles webpack and PostCSS play in adding Tailwind to a Phoenix app.

Webpack Meets PostCSS

Out of the box, Phoenix 1.4 uses webpack to build web assets. So you can think of webpack as the main pipeline for processing CSS. And by default, that pipeline is really simple as it only supports vanilla CSS. Phoenix doesn’t make any assumptions about your CSS preferences.

Tailwind CSS is a PostCSS plugin. Like webpack, PostCSS is a pipeline for processing CSS. Actually, PostCSS itself is just a tool that runs a series of PostCSS plugins which in turn transform CSS in various ways. For example, the autoprefixer plugin adds vendor prefixes such as -webkit, -moz, and -ms to CSS. And the tailwindcss plugin finds Tailwind directives in CSS and replaces them with CSS generated by Tailwind.

The trick then is tying the two pipelines together—the webpack pipeline and the PostCSS pipeline—so that webpack runs the PostCSS plugins at the appropriate step in the build process. To do that we use something called a webpack “loader”. In particular, we use the postcss-loader which effectively injects the PostCSS pipeline into webpack’s pipeline.

Here’s a way to visualize the two pipelines and how they transform CSS:

Anyway, keeping that in mind, we’re ready to wire everything together…

1. Install NPM Packages

First we need the tailwindcss and postcss-loader packages which are both available on NPM. Just make sure to jump into the assets directory before installing them:

cd assets

npm install tailwindcss postcss-loader --save-dev

2. Configure PostCSS

Next we need to tell PostCSS to use the tailwindcss and autoprefixer plugins. To do that, in the assets directory create a PostCSS config file named postcss.config.js and slip this in:

module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer')
  ]
}

This exports an object with a plugins key whose value is an array of PostCSS plugins to use. The order matters here. Remember, we’re building a CSS pipeline. Since Tailwind doesn’t include any vendor prefixes in the CSS it generates, we take care of that by adding the autoprefixer plugin after the tailwindcss plugin. The autoprefixer plugin isn’t required, but I use it in all my projects.

3. Configure webpack

With PostCSS ready to go, we just need to tie it into webpack using the postcss-loader. Crack open the assets/webpack.config.js file and you’ll see all the webpack configuration in its full glory. You’re looking for the following section:

{
  test: /\.css$/,
  use: [MiniCssExtractPlugin.loader, "css-loader"]
}

That’s the CSS rule. It tells webpack to process CSS files using the array of loaders specified by the use property. Again, the order matters here. We need to add the postcss-loader after the css-loader, like so:

use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader"]

And that ties the two pipelines together.

4. Inject Tailwind Into the CSS

Now we’re ready to pull all the Tailwind goodies into our application’s CSS. To do that, hop into the assets/css/app.css file and drop in these three Tailwind directives:

@tailwind base;

@tailwind components;

@tailwind utilities;

When the webpack build process kicks in and the tailwindcss plugin gets its turn, it will replace each of these directives with CSS generated by Tailwind: it’s base styles, component classes, and utility classes.

While you’re in that file, you’ll notice it’s also pulling in the default Phoenix styles:

@import "./phoenix.css";

When I’m using Tailwind I generally don’t use the Phoenix styles, so I remove that line and also delete the corresponding assets/css/phoenix.css file. Totally your call.

5. Use Tailwind Utility Classes

Now fire up your Phoenix server, and you should be able to use Tailwind utility classes in any of your view templates. For example, this should give you a Phoenix-colored heading:

<h1 class="text-orange-500 text-5xl font-bold text-center">Tailwind CSS</h1>

And if you peek at the generated CSS that’s been processed through PostCSS (it’s in priv/static/css/app.css) you’ll see it includes all the Tailwind base styles, component classes, and utility classes which were added by the tailwindcss plugin. As well, you’ll notice that vendor prefixes were automatically added by the autoprefixer plugin.

And that’s all there is to a basic setup! Most of the time that’s all I need. But sometimes I need to go beyond the basics. In the following sections you’ll find answers to some common scenarios and use cases.

Customizing Tailwind

With this setup you can configure and customize Tailwind just as you would if you were using Tailwind outside of Phoenix.

You just need to create a Tailwind config file in your assets directory, which you can do using:

cd assets

npx tailwind init

You’ll get a default config file named tailwind.config.js that Tailwind looks for by default. In that file you can customize Tailwind any way you like.

Where To Put Custom CSS

If you have an existing app that already has custom CSS, then it’s likely you’ll want to continue using it. The easiest way to add custom CSS is to put it in a separate file and import that file at the end of the assets/css/app.css file, like so:

@tailwind base;

@tailwind components;

@tailwind utilities;

@import "./custom-styles.css";

By putting it at the end you avoid any potential specificity issues. And aren’t those fun to sort out?!

Using Custom Component Classes

It’s often handy to extract repeated combinations of Tailwind utility classes and encapsulate them in a custom component class. Buttons are a prime example because you typically use the same button style on multiple pages. That’s where Tailwind’s @apply directive comes in. For example, if your app has indigo-colored buttons you can create a custom component class named btn-indigo like so:

@tailwind base;

@tailwind components;

.btn-indigo {
  @apply bg-indigo-700 text-white font-bold py-2 px-4 rounded;
}

@tailwind utilities;

You just need to make sure to add custom component classes between the @tailwind components directive and the @tailwind utilities directive.

Adding custom component classes in your top-level app.css file like this works well for most projects. You typically only need a handful of component classes. And so having everything in one file is relatively manageable.

However, you may run into situations where you want to organize custom component classes in separate files. You might think (as I did) that you could just move the btn-indigo class into a ./components/buttons.css file and import it, like this:

@tailwind base;

@tailwind components;

@import "./components/buttons.css";

@tailwind utilities;

But that fails silently. It’s only when you look at the generated CSS that you notice it includes the contents of the ./components/buttons.css file verbatim. Sadly, the @apply directive in that file doesn’t get resolved as you’d expect.

Solving this involves using the postcss-import plugin, which you can install using npm:

cd assets

npm install postcss-import --save-dev

Then you need to add it as the first plugin in your postcss.config.js file, like so:

module.exports = {
  plugins: [
    require("postcss-import"),
    require("tailwindcss"),
    require("autoprefixer")
  ]
};

Finally, and this part is crucial, in assets/css/app.css you must import the Tailwind files using @import statements rather than @tailwind directives:

@import "tailwindcss/base";

@import "tailwindcss/components";

@import "./components/buttons.css";

@import "tailwindcss/utilities";

Why? Because postcss-import requires that all @import statements be at the top of the file. It’s for a good reason: that’s what the CSS spec dictates. So changing the @tailwind directives to @import statements keeps everything in the proper order and compliant with the spec.

Purging Unused CSS

Tailwind generates a ton of CSS utility classes by default. Every shade of color can be used for text, backgrounds, and borders. Every size on the sizing scale can be used for margin, padding, width, height, and so on. And every responsive breakpoint has it’s own copy of all these utility classes. So yeah, that adds up to a lot of CSS.

And that’s great during development because it means you have literally thousands of utility classes at your fingertips. As you’re probably already thinking though, it’s a hefty amount of CSS to put into production.

Good news: You won’t use most of those utility class in your app and purgecss does a great job of removing unused CSS. In a nutshell, it analyzes your content files and CSS to determine which CSS selectors are being used, and removes unused selectors from the generated CSS.

To set it up in production, first install @fullhuman/postcss-purgecss:

cd assets

npm install @fullhuman/postcss-purgecss --save-dev

It’s another PostCSS plugin that needs to get configured and added to the list of PostCSS plugins in the postcss.config.js file. Here’s a version of that file with purging enabled only in production:

const purgecss = require('@fullhuman/postcss-purgecss')({
  content: ["../**/*.html.eex", "../**/views/**/*.ex", "./js/**/*.js"],
  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
})

module.exports = {
  plugins: [
    require("postcss-import"),
    require("tailwindcss"),
    require("autoprefixer"),
    ...(process.env.NODE_ENV === "production" ? [purgecss] : [])
  ]
};

This is a fairly boilerplate configuration for using purgecss with Tailwind. More details can be found in the Tailwind documentation.

The only thing specific to Phoenix is the content section on the second line which tells purgecss where to find content files to analyze. These are the files that may be using a Tailwind utility class. In a Phoenix app that means all the template files, view modules, and JavaScript files.

It’s worth noting that there are cases when you don’t want purgecss to remove certain CSS classes. For example, Tailwind recommends only applying purgecss to Tailwind’s utility classes, not its base styles and component classes. Here’s how to do that in your app.css file:

/* purgecss start ignore */

@tailwind base;
@tailwind components;

/* purgecss end ignore */

@tailwind  utilities;

The special purgecss comments tell it to ignore certain CSS classes, in this case the classes in Tailwind’s base styles and components. Said another way, this whitelists the CSS classes in the base and components files to prevent purgecss from removing those classes from your CSS.

I hope that helps put the wind at your back as you design custom UIs in Phoenix!