Tasnim Zotder

How to use Tailwind CSS with Next.js?

Author: Tasnim Zotder
WebProgrammingHow To

What is Tailwind CSS?

Tailwind CSS is a JavaScript library that provides a set of utility classes to style we applications. Tailwind CSS can be used with most of the front-end frameworks like React, Vue, Angular, etc. It is a tool for creating reusable, maintainable stylesheets. Besides, it is a CSS framework that is highly customizable and can be used with CSS preprocessor like Sass, Less, etc.

Steps to use Tailwind CSS with Next.js

The following steps will help you to use Tailwind CSS with Next.js.

1. Install the dependencies

First, you need to install the dependencies. You can install the dependencies by running the following command.

if you are using yarn then run the following command.

yarn add -D tailwindcss@latest postcss@latest autoprefixer@latest

if you are using npm then run the following command.

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

2. Create the config file

Next, you need to create the config file for Tailwind CSS. You can create the config file by running the following command.

yarn tailwind init -p

This will create a tailwind.config.js file in the root directory. You can customize the config file as per your requirement.

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

This command also creates a postcss.config.js file.

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

3. Configure Tailwind CSS

In tailwind.config.js file, configure the purge option with the paths to all the pages & components so Tailwind can tree-shake unused styles in production build.

tailwind.config.js
...
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}']
...

4. Include Tailwind in CSS

Open the styles/global.css file and include the following lines.

styles/global.css
@tailwind base;
@tailwind components;
@tailwind utilities;

5 Add Tailwind CSS IntelliSense to VS Code

For the code autocomplete to work, you need to install the vscode-tailwindcss extension. This extension will add the Tailwind CSS IntelliSense to VS Code. Tailwind CSS IntelliSense.