How To Use Tailwind CSS with Next.js
In this guide, we'll walk through how to install Tailwind CSS in a Next.js project. If you are on version 9.2 or above, there's an even simpler way!
1Create a new project
If you are starting fresh, run the following command to create a new Next.js project. Otherwise, you can proceed with these steps to add Tailwind to an existing Next.js app.
npm create next-app next-js-tailwindcd next-js-tailwind
2Install dependencies
Run the following to install Tailwind and a few other dependencies:
npm install tailwindcss autoprefixer postcss-loader --save-devnpm 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. This tells Next.js to process CSS files that you import
in your code.
const withCSS = require('@zeit/next-css');module.exports = withCSS({});
4Add Tailwind to your CSS
Create a CSS file in a styles
directory and add the Tailwind directives:
mkdir styles && touch styles/main.csscat >styles/main.css <<EOL@tailwind base;@tailwind components;@tailwind utilities;EOL
5Import your CSS
If you don't already have a custom pages/_app.js
file, create one like this:
import '../styles/main.css';function App({ Component, pageProps }) {return <Component {...pageProps} />;}export default App;
If you already have a custom app file, just add the import
for your stylesheet. That's it! You can now start using Tailwind CSS utilities in your className
attributes!