Skip to content

Next.js Tailwind CSS

Tailwind CSS is a utility-first CSS framework that provides a set of atomic CSS classes, allowing you to quickly build modern user interfaces directly in HTML. The integration between Next.js and Tailwind CSS is very smooth. This chapter will guide you through setting up and using Tailwind CSS in your Next.js project.

1. Why Choose Tailwind CSS?

  • Rapid Development: By composing utility classes, you can quickly implement complex designs without writing custom CSS.
  • Constrained Design: Predefined design systems (colors, spacing, font sizes, etc.) help maintain UI consistency.
  • High Performance: With PurgeCSS (built into Tailwind CSS v2.0+), unused CSS in production is automatically removed, generating extremely small CSS files.
  • Customizable: Easily extend or modify the default design system through the tailwind.config.js file.

2. Installing and Configuring Tailwind CSS in Next.js

Starting from Next.js 12, official built-in support for Tailwind CSS is provided, making the integration process very simple.

Step 1: Create a Next.js Project

If you don't have a project yet, you can use create-next-app with the Tailwind CSS option:

bash
npx create-next-app@latest my-app --tailwind --eslint
cd my-app

This will automatically configure all necessary files for you.

Step 2: Manual Installation and Configuration

If you want to add Tailwind CSS to an existing project, follow these steps.

  1. Install dependencies:

    bash
    npm install -D tailwindcss postcss autoprefixer
  2. Generate configuration files:

    bash
    npx tailwindcss init -p

    This command creates two important files:

    • tailwind.config.js: For configuring Tailwind CSS.
    • postcss.config.js: For configuring PostCSS, which Next.js automatically uses.
  3. Configure tailwind.config.js:

    Open the tailwind.config.js file and configure the content field to tell Tailwind CSS which files to scan for used classes.

    js
    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        './pages/**/*.{js,ts,jsx,tsx,mdx}',
        './components/**/*.{js,ts,jsx,tsx,mdx}',
        './app/**/*.{js,ts,jsx,tsx,mdx}', // If using App Router
      ],
      theme: {
        extend: {},
      },
      plugins: [],
    }
  4. Import Tailwind in global CSS:

    Open the styles/globals.css file and replace its contents with the following to import Tailwind's base styles, components, and utilities.

    css
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
  5. Import global styles in _app.js:

    Make sure the styles/globals.css file is imported in pages/_app.js.

    jsx
    // pages/_app.js
    import '../styles/globals.css';
    
    function MyApp({ Component, pageProps }) {
      return <Component {...pageProps} />;
    }
    
    export default MyApp;

3. Using Tailwind CSS in Components

After completing the above configuration, you can use Tailwind CSS utility classes directly in any component or page.

Example: Creating a responsive card component

jsx
// components/Card.js

export default function Card({ title, children }) {
  return (
    <div className="max-w-sm rounded-lg overflow-hidden shadow-lg bg-white p-6 m-4">
      <div className="font-bold text-xl mb-2 text-gray-800">{title}</div>
      <p className="text-gray-700 text-base">
        {children}
      </p>
      <div className="mt-6">
        <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full transition duration-300 ease-in-out">
          Learn More
        </button>
      </div>
    </div>
  );
}

Using the component in a page:

jsx
// pages/index.js

import Card from '../components/Card';

export default function HomePage() {
  return (
    <div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center">
      <h1 className="text-4xl font-bold text-center text-blue-600 mb-8">
        Welcome to Next.js with Tailwind CSS
      </h1>
      <div className="flex flex-wrap justify-center">
        <Card title="Declarative UI">
          Tailwind CSS allows you to build complex user interfaces by composing simple utility classes.
        </Card>
        <Card title="Responsive Design">
          Use responsive modifiers like `md:` and `lg:` to build adaptive layouts for any screen size.
        </Card>
      </div>
    </div>
  );
}

4. Advanced Usage

Custom Themes

You can customize the design system by modifying the theme object in tailwind.config.js. For example, adding custom colors or fonts.

js
// tailwind.config.js
module.exports = {
  // ...
  theme: {
    extend: {
      colors: {
        'brand-blue': '#1992d4',
        'brand-green': '#42b983',
      },
      fontFamily: {
        sans: ['Inter', 'sans-serif'],
      },
    },
  },
  // ...
}

Now you can use custom classes like bg-brand-blue or font-sans in your project.

Using @apply to Extract Component Classes

If you find yourself repeatedly using the same utility class combinations, you can use the @apply directive to extract them into custom CSS classes.

styles/components.css (needs to be imported into globals.css):

css
@layer components {
  .btn-primary {
    @apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full transition duration-300;
  }
}

Then you can use class="btn-primary" in HTML.

Note: Overusing @apply may go against Tailwind's philosophy. It's generally recommended to prioritize utility classes and only extract component classes when necessary.

Summary

Combining Tailwind CSS with Next.js can greatly improve development efficiency and UI consistency. With simple configuration, you get a powerful and highly customizable styling solution. In the next chapter, we'll learn how to handle static assets like images and fonts in Next.js.

Content is for learning and research only.