Get up and running with TailwindCSS in Next.js

date
Nov 19, 2020
slug
nextjs-tailwindcss-start
status
Published
tags
Next.js
TailwindCSS
summary
Adding TailwindCSS v2 to your already amazing Next.js project.
type
Post
TailwindCSS v2 was recently released. Their release trailer was freaking amazing. They even got music composed especially for their trailer. You can check out the youtube video here.
Now let's focus on how you can add TailwindCSS v2 to your new or existing Next.js project.

Creating a new Next.js project

npx create-next-app your-project-name
This command will bootstrap a new Next.js project for you. The package.json should contain these scripts.
"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start"
}
You can start the project by running
npm run dev

Adding TailwindCSS

npm install tailwindcss postcss autoprefixer
PostCSS v8 or up is required for Tailwind v2 to work. autoprefixer is a PostCSS plugin. It adds vendor-specific prefixes to the compiled CSS like -webkit, -ms, etc.

Configuring PostCSS

Both tailwindcss and autoprefixer are postcss plugins. To use them in our project, we first need to configure postcss and pass these two plugins to it.
Create a file named postcss.config.js in the root of your project.
touch postcss.config.js
Now add this to the file.
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

Adding TailwindCSS styles

Now create a src/styles/tailwind.css file and add the following to it.
@tailwind base;
@tailwind components;
@tailwind utilities;
The @tailwind directive will inject the base, components, and utility classes for us to use.
Now we have added TailwindCSS to our project. The only thing remaining is importing the styles globally. Doing so will let us use them from anywhere in our project. To do that let import the tailwind.css file into the pages/_app.js file.
import '../src/styles/tailwind.css';

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

export default App;
Restart your server after making changes to pages/_app.js so the changes can reflect.
Now you are ready to use Tailwind v2 in your project. Let's try it now, shall we?
Remove everything from your pages/index.js file and paste this there.
export default function Home() {
  return (
    <h1 className="text-4xl text-red-400 bg-gray-800 p-4 text-center">
      TailwindCSS v2 with Next.js
    </h1>
  );
}
notion image

Configuring TailwindCSS defaults

To change the TailwindCSS defaults we first need to create a tailwind config file. Add it by running this command.
npx tailwindcss init
This will create tailwind.config.js in the root of your project with following content,
module.exports = {
  purge: [],
  darkMode: false,
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}

© Nikit Singh 2020 - 2024