How To Use Tailwind CSS with Next.js
In this guide, we'll walk through how to install Tailwind CSS in a new Next.js project.
1Create 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.
2Install 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
3Configure 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.
4Add 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
5Import 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!