Using Tailwind CSS with Next.js

In this guide, we'll walk through how to install Tailwind CSS in a new Next.js project.

Here's a working version of what you'll end up creating:

1
Create a new project

Run the following command to create a fresh project:

npm init next-app next-js-tailwind

This command will make a new directory, add a package.json file with the necessary dependencies and script definitions, and scaffold a sample home page for you.

To boot up your local development server, run the following:

cd next-js-tailwind
npm run dev

You should see "Welcome to Next.js" when you open http://localhost:3000/ in your browser.

2
Install dependencies

Run the following to install Tailwind and its other dependencies:

npm install tailwindcss autoprefixer postcss-loader --save-dev

You'll also need to install the next-css plugin:

npm install @zeit/next-css

3
Configure the build pipeline

Create a postcss.config.js file with the following:

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

Then, create a next.config.js file and wrap your config with the withCSS function:

const withCSS = require('@zeit/next-css');

module.exports = withCSS({});

This tells Next.js to process CSS files that you import in your code.

4
Add Tailwind to your CSS

Create a CSS file in a styles directory and add the Tailwind directives:

mkdir styles && touch styles/main.css

cat >styles/main.css <<EOL
@tailwind base;
@tailwind components;
@tailwind utilities;
EOL

5
Import your CSS

Open up pages/index.js and add your import:

  import React from 'react'
  import Link from 'next/link'
  import Head from 'next/head'
  import Nav from '../components/nav'
+
+ import '../styles/main.css'

  const Home = () => (
    <div>
      <Head>
        <title>Home</title>
      </Head>

Eventually, you may wish to import your CSS in a custom <App> component to ensure it gets loaded on every page.

You can now start using Tailwind CSS utilities in your className attributes!

Check out the source on GitHub →