Tailwind CSS is the hottest CSS framework in the past few years: it's fun and easy to use, with wonderful defaults that make designing beautiful UIs a breeze.
To install TailwindCSS in your Next.js project, run the following command:
npm install -D tailwindcss postcss
Initialize the Tailwind CSS configuration
Afterward, we run the following command to initialize the Tailwind configuration:
npx tailwindcss init
This will create a file named tailwind.config.js
in your root folder. We have to change the content
glob to use files with the tsx
extension:
/** @type {import('tailwindcss').Config} */ module.exports = { content: ["./**/*.{tsx}"], theme: { extend: {}, }, plugins: [],}
Add the PostCSS configuration file
Additionally, we have to create a postcss
configuration that Next.js will automatically pick up. To do so, create a file names postcss.config.js
in your root folder and add the following content:
module.exports = { plugins: { tailwindcss: {}, },};
Import Tailwind CSS in your styles
At this point, we have to import Tailwind CSS in your global styles, normally located at styles/index.css
. To do so add the following content to your main CSS file:
@tailwind base;@tailwind components;@tailwind utilities;
To test if this works, visit your home page at pages/index.tsx
and add some styles such as:
<h1 className='text-5xl'> This is Tailwind CSS with Next.js!</h1>
Installing the Tailwind CSS Prettier plugin
If you're using Prettier, you can install a plugin to automatically sort the class names in your HTML tags according to the best practices prescribed by the Tailwind CSS team, so to make your code clean and consistent.
To install the Prettier plugin, use the following command:
npm i prettier-plugin-tailwindcss
If it's all good, you don't have to do anything else, it will simply work when running Prettier, which we recommend doing each time you save your files.