Use Tailwind CSS with CSS Modules in Next.js



When using Tailwind CSS in a Next.js project, it's common to apply utility classes for styling. However, if you're using CSS Modules, it can be difficult because the styles are scoped locally. The @apply directive in Tailwind allows you to combine multiple utility classes into one rule, making it easier to use Tailwind with CSS Modules.

Our goal is to show you how to set up Tailwind CSS with CSS Modules in a Next.js project and use the @apply directive properly.

Approaches

Here, we will cover two approaches for using Tailwind's @apply inside CSS Modules in a Next.js project.

Steps to Set Up Tailwind CSS with Next.js

First, we'll show you how to set up Tailwind CSS with Next.js.

Step 1: Install Node.js from here if it's not already installed.

Step 2: Run the following command to create a new Next.js project:

npx create-next-app@latest

You'll be prompted with questions to customize your setup. Select Yes for Tailwind CSS and No for others, based on your needs:

What is your project named? my-sample-app
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? Yes
Would you like to use `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to customize the default import alias? No / Yes

Step 3: Once the setup is complete, navigate into your project directory:

cd my-sample-app

Step 4: If Tailwind CSS isn't installed, run the following to create tailwind.config.js:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

In your tailwind.config.js, set the content paths like this:

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

Project Structure:

project Structure

Step 5: Run the following command and open http://localhost:3000 in your browser:

npm run dev

Using @apply Inside CSS Modules

In this approach, we apply Tailwind CSS utilities inside a CSS Module for a specific component. This method ensures that styles are scoped locally to the component while still using Tailwind's utility classes.

Steps we have taken:

First, we created a Card.module.css file in the components folder. In this file, we used the @apply directive from Tailwind CSS to apply utility classes:

/* components/Card.module.css */
.card {
    @apply bg-white shadow-lg rounded-lg p-6 border-2 border-indigo-500;
}

.cardTitle {
    @apply text-2xl font-semibold text-indigo-700 mb-2;
}

.cardContent {
    @apply text-gray-600 text-base;
}

Next, we created the card component in the components/Card.js file, where we imported and applied the styles from the CSS module:

// components/Card.js
import styles from './Card.module.css';

const Card = () => {
    return (
        <div className={styles.card}>
        <h1 className={styles.cardTitle}>We Welcome You!!</h1>
        <p className={styles.cardContent}>
            Learn and grow with <span className="text-green-500">
                tutorialspoint
            </span>.
        </p>
        </div>
    );
};

export default Card;

Then, we used the card component in the pages/index.js file:

//pages/index.js
import Card from '../components/Card';

export default function Home() {
    return (
        <div className="flex justify-center items-center 
                    h-screen bg-blue-100">
            <Card />
        </div>
    );
}

Finally, we run the following command to start the development server:

npm run dev

Now, you can open your browser and see the output.

Output

Output of first approach

Using @apply in Global Styles with CSS Modules

In this approach, we use @apply in a global CSS file to set common styles that can be used in multiple components. This is great for ensuring consistency, like for buttons or layout elements, that are used throughout the entire app.

Steps we took:

We first created two separate button components inside the components folder:

  • Primary Button (components/PrimaryButton.js):
// components/PrimaryButton.js
const PrimaryButton = () => {
    return (
    <button className="btn-primary">
        Learn at TutorialsPoint
    </button>
    );
};

export default PrimaryButton;
  • Secondary Button (components/SecondaryButton.js):
  • // components/SecondaryButton.js
    const SecondaryButton = () => {
        return (
            <button className="btn-secondary">
            Explore TutorialsPoint
            </button>
        );
    };
      
    export default SecondaryButton;
    

    Next, we updated the styles/global.css file to apply Tailwind utility classes using the @apply directive for global button styles:

    /* styles/global.css */
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    /* Base styles for the app */
    @layer base {
        body {
            @apply bg-gray-50 font-sans text-gray-900;
        }
    }
    
    /* Button styles */
    @layer components {
        .btn-primary {
            @apply bg-gradient-to-r from-purple-500 to-blue-700 text-white py-3 px-8 rounded-full font-semibold text-xl shadow-2xl; 
        }
    
        .btn-secondary {
            @apply bg-gradient-to-r from-emerald-500 to-green-700 text-white py-3 px-8 rounded-full font-semibold text-xl shadow-2xl;
        }
    }
    

    We then imported the globals.css file in the pages/_app.js so that the styles would apply across the entire app:

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

    After that, we used the PrimaryButton and SecondaryButton components inside index.js:

    // pages/index.js
    import PrimaryButton from '../components/PrimaryButton';
    import SecondaryButton from '../components/SecondaryButton';
    
    export default function Home() {
        return (
            <div className="flex justify-center items-center h-screen 
                    bg-gray-50 space-x-6">
                <PrimaryButton />
                <SecondaryButton />
            </div>
        );
    }
    

    Finally, we run the following command to start the development server:

    npm run build
    

    Output

    Output of second approach

    Conclusion

    This article covered two ways to use Tailwind CSS with CSS Modules in Next.js: applying utilities inside CSS Modules for component-specific styling and using @apply in global styles for consistent designs. Both methods enable efficient and scalable styling in Next.js with Tailwind's utility-first approach.

    Updated on: 2025-01-06T10:42:50+05:30

    97 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements