Using Tailwind with Phoenix

A quick tutorial on getting up and running with CSS utilities.

Tailwind CSS is a utility-first CSS framework for rapidly building custom designs. As someone who tends to design in the browser (instead of apps like Sketch), adopting the utility paradigm has been a game changer for my productivity. It also plays well with your existing CSS, so you can safely dip your toe in the water without doing a Big Rewrite.

Prerequisites

  • Phoenix ~> 1.4
  • Tailwind ~> 1.0
  • Webpack ~> 4.0

Tested with Phoenix 1.4.8, Tailwind 1.0.4, and Webpack 4.4.0

Install dependencies

From the root of your Phoenix application, run the following to install Tailwind and PostCSS Loader:

cd assets
npm install tailwindcss --save-dev
npm install postcss-loader --save-dev

Wire up Webpack

In your assets directory, create a PostCSS config file with the following contents:

// postcss.config.js

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

Open up your Webpack config file and update your CSS rule to include postcss-loader:

// webpack.config.js

module.exports = (env, options) => ({
  // ...
  module: {
    rules: [
      // ...
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: 'css-loader', options: { importLoaders: 1 } },
          'postcss-loader'
        ]
      },
      // ...
    ]
  },
  // ...
});

Import Tailwind in your stylesheet

In your app.css file, include the Tailwind directives:

/* app.css */

@tailwind base;

@tailwind components;

/* Put your custom components here */

@tailwind utilities;

/* Put your custom utilities here */

Customize Tailwind (Optional)

At this point, you’re all set up to work with Tailwind’s excellent defaults.

If you need to customize your configuration, all you need to do is create a Tailwind config file in your assets directory:

cd assets
npx tailwind init

That’s it! Happy designing.

Newsletter

Join 1,900+ people following along as I build my next company.