Tailwind CSS

Tailwind CSS はユーティリティファーストの CSS フレームワークで、Next.js と非常に相性が良いです。

Tailwind のインストール

Tailwind CSS パッケージをインストールし、init コマンドを実行して tailwind.config.jspostcss.config.js ファイルを生成します:

ターミナル
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Tailwind の設定

tailwind.config.js 内で、Tailwind CSS クラス名を使用するファイルのパスを追加します:

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './app/**/*.{js,ts,jsx,tsx,mdx}', // `app` ディレクトリの追加に注意
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',

    // `src` ディレクトリを使用する場合:
    './src/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

postcss.config.js を変更する必要はありません。

スタイルのインポート

Tailwind が生成したスタイルを注入するために使用する Tailwind CSS ディレクティブ を、アプリケーションの グローバルスタイルシート に追加します。例:

app/globals.css
@tailwind base;
@tailwind components;
@tailwind utilities;

ルートレイアウト (app/layout.tsx) 内で、globals.css スタイルシートをインポートして、アプリケーションのすべてのルートにスタイルを適用します。

import type { Metadata } from 'next'

// これらのスタイルはアプリケーションのすべてのルートに適用されます
import './globals.css'

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}
// これらのスタイルはアプリケーションのすべてのルートに適用されます
import './globals.css'

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}

クラスの使用

Tailwind CSS をインストールし、グローバルスタイルを追加した後、アプリケーションで Tailwind のユーティリティクラスを使用できます。

export default function Page() {
  return <h1 className="text-3xl font-bold underline">Hello, Next.js!</h1>
}
export default function Page() {
  return <h1 className="text-3xl font-bold underline">Hello, Next.js!</h1>
}

Turbopack での使用

Next.js 13.1 以降、Turbopack で Tailwind CSS と PostCSS がサポートされています。