Integrating Tailwind CSS with a Next.js project is straightforward. Below are the steps to set up a new Next.js project with Tailwind CSS:
Installation
-
Create a Next.js Project: If you haven't already, start by creating a new Next.js project.
npx create-next-app my-nextjs-project
Navigate into your project folder:
cd my-nextjs-project
-
Install Tailwind CSS: Inside the project folder, install Tailwind CSS, along with its dependencies.
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
Configuration
-
Generate Configuration Files: Generate configuration files for Tailwind CSS and PostCSS. This will create a tailwind.config.js and a postcss.config.js file in your project root.
npx tailwindcss init -p
-
Configure Tailwind: Open tailwind.config.js and configure it as needed. For starters, you don't have to change anything.
// tailwind.config.js
module.exports = {
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
-
Configure PostCSS: Open postcss.config.js and make sure it looks like this:
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
Integration
-
Integrate Tailwind in Global Styles: Open the styles/globals.css file and import Tailwind's styles:
/* ./styles/globals.css */
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
-
Update _app.js: Make sure your pages/_app.js imports this global stylesheet:
// pages/_app.js
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
Usage
Now, you can start using Tailwind CSS classes in your Next.js components:
// Example in pages/index.js
export default function Home() {
return (
<div className="flex items-center justify-center h-screen bg-gray-100">
<h1 className="text-4xl font-bold text-blue-500">
Welcome to Next.js with Tailwind CSS!
</h1>
</div>
)
}
To start your Next.js development server, run:
npm run dev
Your Next.js project should now be set up to use Tailwind CSS.
Optional: JIT Mode
As of Tailwind CSS v2.1+, you can enable Just-In-Time (JIT) mode by simply adding the mode option in your tailwind.config.js:
// tailwind.config.js
module.exports = {
mode: 'jit', // enable JIT
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
// ...rest of the config
}
JIT mode provides various benefits like faster build times and on-the-fly class generation.
And that's it! You've successfully integrated Tailwind CSS with Next.js.