Tailwind is a popular utility first CSS framework for rapidly building custom User Interfaces. It provides low-level classes, those classes combine to create styles for various components. You can learn more about Tailwind CSS here.
Next.js: Next.js is a React-based full-stack framework developed by vertical that enables functionalities like pre-rendering of web pages. Unlike traditional react app where the entire app is loaded on the client, Next.js allow the web page to be rendered on the server, which is great for performance and SEO. You can learn more about Next.js here.
In this article, we will learn how to set up Tailwind CSS with Next.js. Before installing Tailwind CSS, make sure you have node and npm installed.
Step 1: Create a new Next Project:
You can create a new Next application using the command below.
npx create-next-app gfg
Step 2: Install Tailwind
Once your next project is created, open the project’s root directory and install the tailwind dependencies with the following command.
npm install -D tailwindcss postcss autoprefixer
Step 3: Create Tailwind config file
Run the following command to create a tailwind config file, this file can be used to extend the tailwind’s functionality.
npx tailwindcss init -p
The above command will create two configuration files in your project.
./tailwind.config.js
module.exports = { content: [], theme: { extend: {}, }, plugins: [], } |
./postcss.config.js
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, } |
Project Structure: Following is the project structure after installing tailwind CSS.
Step 4: Configure template paths
We need to configure file paths, for tailwind to work. So, in your tailwind.config.js file, add the following configuration.
module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [], }
This configuration is only for pages and components directory, you can also configure your custom folders here.
Step 5: Add Tailwind directives
In your /styles/global.css file, add the layer directives of tailwind CSS.
@tailwind base; @tailwind components; @tailwind utilities;
Step 6: Testing Tailwind CSS
Now that we have set up the tailwind CSS, let’s test it out. In the /pages/index.js file, we will first clean all the boilerplate code and test some utility classes from Tailwind CSS.
/pages/index.js
import React from 'react' const HomePage = () => { return ( <div className= 'text-3xl text-green-600 p-2' > Hello Geeks! </div> ) } export default HomePage |
Step to run the application: We can run our next application using the following command.
npm run dev