Blog>
Snippets

Setting Up Tailwind CSS in Next.js 14

Show how to install and configure Tailwind CSS in a Next.js 14 project using the new `app` directory and demonstrating how to customize the Tailwind configuration file.
const { execSync } = require('child_process');

// Install Tailwind CSS dependencies
execSync('npm install -D tailwindcss postcss autoprefixer');

// Create Tailwind config and PostCSS files
execSync('npx tailwindcss init -p');
This JavaScript code uses Node.js to install Tailwind CSS and its dependencies and to generate the Tailwind configuration and PostCSS files via the command line.
// tailwind.config.js
module.exports = {
  content: ['./app/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};
This is the Tailwind CSS configuration file, where you specify the paths to all of your template files and customize your design system.
// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};
This is the PostCSS configuration file, which includes Tailwind CSS as a plugin, along with autoprefixer for handling CSS vendor prefixes.
/*
  Create a global CSS file in your Next.js project under the "app" directory,
  for example: app/styles/globals.css and add the following Tailwind directives:
*/

@tailwind base;
@tailwind components;
@tailwind utilities;
This snippet should be placed in a CSS file (e.g., app/styles/globals.css). These directives include Tailwind's base, components, and utilities styles, which are necessary for using Tailwind CSS in your project.
// In the _app.js or _app.tsx file, import the global CSS file

import '../styles/globals.css';

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}
This code imports the global CSS file in the custom App component (located at app/_app.js or app/_app.tsx) ensuring that Tailwind CSS styles are included in the project.