Configure Tailwindcss in Next.js

Cover Image for Configure Tailwindcss in Next.js
Ali Bentaleb
Ali Bentaleb

Tailwind let you rapidly build modern websites without ever leaving your HTML. It consists of class names that you can use out of the box and paint your HTML very quickly.

To configure tailwindcss in a Next.js project, you need to:

First step: use the latest tailwindcss version

In order to have default animations provided by tailwindcss, make sure you are using the latest version for tailwindcss, postcss and autoprefixer.

To do so, run the following command:


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

Second step: generate tailwindcss configurations files

Next, you need to generate configuration files needed by tailwindcss

npx tailwindcss init -p

Once done, you should see tailwind.config.js and postcss.config.js files added to your project root directory.

Third step: add tailwind directives to a global CSS file

You need to copy then these directives to a global CSS file, for example let's name it globals.css under styles folder, and add the following:


@tailwind base;
@tailwind components;
@tailwind utilities;

Fourth step: add globals.css to _app.js file

Create a specific file named _app.js under pages folder if not already done and include your globals.css in it.

_Tip: whatever name you give to the file containing the tailwindcss directives should be included in /\_app.js, so if the directives are contained in \_index.css_ file, just include your index.css in /\_app.js with import ../styles/index.css.

Your file should look like this

import "../styles/globals.css";

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;

}

export default MyApp;

configure tailwind.config.js

copy this to the file


module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],

}

You can always refer to tailwindcss doc to integrate it with nextjs in this link

Conclusion

We have seen how to configure tailwindcss with Next.js, to check more articles about next.js articles, check this link

How to build animated spinner ...How to solve Can't perform a R...