SimpleNext.js

How to use Tailwind in your Next.js project

Cover Image for How to use Tailwind in your Next.js project
Marouane Reda
Marouane Reda

Tailwindcss is an increasingly popular utility-first CSS framework that focuses on productivity by providing out of the box classes like flex, pt-4, text-center and rotate-90 that can be composed to build any design, directly in your markup.

Check out the official page to learn more.

Why you should use Tailwind in your Next.js project :

  • meaningful variables : by using text-center to center you text, or text-lg for large text, you will save a lot of time
  • predefined classes : Because Tailwind CSS has already defined all CSS classes, you aren't able to specify any random number for your margin, padding, font-size, etc… so you will avoid adjusting pixel by pixel or drowning in multiple shades of red

Cons of Tailwind :

  • Learning curve : you will need some time to learn the most used classes and always get back to the - great - documentation to search for the class you need
  • No styled components : if you are searching for styled components like for bootstrap or Chakra, you will need to implement it from scratch ( or use TailwindUI, which is not free)
  • Mix HTML and CSS : If you are used to put your css in separate files from your html files, using Tailwind will feel strange as you put CSS directly in HTML

Integrate with Next.js

To integrate Tailwindcss with your next.js project, follow these steps :

Install Tailwind and its dependencies :

If you are on Next.js v10

If you are on Next.js v9 or older

npm install -D [email protected]:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat [email protected]^7 [email protected]^9

Create your configuration files

Next, generate your tailwind.config.js and postcss.config.js files:

npx tailwindcss init -p

This will create a minimal tailwind.config.js file at the root of your project:

// tailwind.config.js
module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

It will also create a postcss.config.js file that includes tailwindcss and autoprefixer already configured:

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

Include Tailwind in your CSS

Open the ./styles/globals.css file that Next.js generates for you by default and use the @tailwind directive to include Tailwind's base, components, and utilities styles, replacing the original file contents:

/* ./styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

You can know use Tailwind in your Next.js project!