コンテンツにスキップ

アプリケーションでCSSを使用する方法

Next.jsは、アプリケーションでCSSを使用するためのいくつかの方法を提供します。これには以下が含まれます。

このページでは、これらの各アプローチを使用する方法について説明します。

CSSモジュール

CSSモジュールは、一意のクラス名を生成することでCSSをローカルスコープに限定します。これにより、異なるファイルで同じクラス名を使用しても、名前の衝突を心配する必要がありません。

CSSモジュールの使用を開始するには、拡張子`.module.css`の新しいファイルを作成し、それを`app`ディレクトリ内の任意のコンポーネントにインポートします。

app/blog/styles.module.css
.blog {
  padding: 24px;
}
app/blog/page.tsx
import styles from './styles.module.css'
 
export default function Page({ children }: { children: React.ReactNode }) {
  return <main className={styles.blog}>{children}</main>
}

グローバルCSS

グローバルCSSを使用して、アプリケーション全体にスタイルを適用できます。

グローバルスタイルを使用するには、`app/global.css`ファイルを作成し、ルートレイアウトでそれをインポートして、アプリケーションの**すべてのルート**にスタイルを適用します。

app/global.css
body {
  padding: 20px 20px 60px;
  max-width: 680px;
  margin: 0 auto;
}
app/layout.tsx
// These styles apply to every route in the application
import './global.css'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}

ヒント: グローバルスタイルは、`app`ディレクトリ内の任意のレイアウト、ページ、またはコンポーネントにインポートできます。ただし、Next.jsはスタイルシートに対するReactの組み込みサポートを使用してSuspenseと統合しているため、現在、ルート間を移動してもスタイルシートが削除されず、競合が発生する可能性があります。*真に*グローバルなCSSにはグローバルスタイルを、スコープ付きCSSにはCSSモジュールの使用をお勧めします。

Tailwind CSS

Tailwind CSS は、Next.jsとシームレスに統合できるユーティリティファーストのCSSフレームワークです。

Tailwindのインストール

Tailwindの使用を開始するには、必要なTailwind CSSパッケージをインストールします。

ターミナル
npm install tailwindcss @tailwindcss/postcss postcss

Tailwindの設定

プロジェクトのルートに`postcss.config.mjs`ファイルを作成し、PostCSSの設定に`@tailwindcss/postcss`プラグインを追加します。

postcss.config.mjs
/** @type {import('tailwindcss').Config} */
export default {
  plugins: {
    '@tailwindcss/postcss': {},
  },
}

Tailwindの使用

グローバルスタイルシートTailwindディレクティブを追加します。

app/globals.css
@import 'tailwindcss';

次に、ルートレイアウトでスタイルをインポートします。

app/layout.tsx
import type { Metadata } from 'next'
// These styles apply to every route in the application
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>
  )
}

その後、アプリケーションでTailwindのユーティリティクラスを書き始めることができます。

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

Sass

Next.jsは、Sassと統合されており、`scss``sass`の両方の拡張子と構文をサポートしています。

また、CSSモジュールと`.module.scss`または`.module.sass`拡張子を介して、コンポーネントレベルのSassも使用できます。

Sassのインストール

Sassの使用を開始するには、`sass`パッケージをインストールします。

ターミナル
npm install --save-dev sass

Sassオプションのカスタマイズ

Sassオプションを設定したい場合は、`next.config.js`の`sassOptions`オプションを使用してください。

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  sassOptions: {
    additionalData: `$var: red;`,
  },
}
 
export default nextConfig

CSS-in-JS

警告: ランタイムJavaScriptを必要とするCSS-in-JSライブラリは、現在React Server Componentsではサポートされていません。Server ComponentsやStreamingのような新しいReact機能でCSS-in-JSを使用するには、ライブラリの作者が最新バージョンのReactをサポートする必要があります。

以下のライブラリは、`app`ディレクトリ内の**クライアントコンポーネント**でサポートされています(アルファベット順)。

以下は現在サポートを開発中です

Server Componentsをスタイリングしたい場合は、CSSモジュールまたはTailwind CSSのようにCSSファイルを出力する他のソリューションを使用することをお勧めします。

CSS-in-JSの設定

CSS-in-JSを設定するには、以下を行う必要があります。

  1. レンダー内のすべてのCSSルールを収集するための**スタイルレジストリ**を作成します。
  2. `useServerInsertedHTML`フックを使用して、ルールを使用する可能性のあるコンテンツの前にルールを挿入します。
  3. 初期サーバーサイドレンダリング中に、スタイルレジストリでアプリをラップするクライアントコンポーネントを作成します。

`styled-jsx`

アプリケーション用に`styled-jsx`を設定するには、新しいレジストリを作成します。

app/registry.tsx
'use client'
 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
 
export default function StyledJsxRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://react.dokyumento.jp/docs/hooks-reference.html#lazy-initial-state
  const [jsxStyleRegistry] = useState(() => createStyleRegistry())
 
  useServerInsertedHTML(() => {
    const styles = jsxStyleRegistry.styles()
    jsxStyleRegistry.flush()
    return <>{styles}</>
  })
 
  return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>
}

次に、ルートレイアウトをレジストリでラップします。

app/layout.tsx
import StyledJsxRegistry from './registry'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledJsxRegistry>{children}</StyledJsxRegistry>
      </body>
    </html>
  )
}

`styled-components`

`styled-components`を使用するには、`next.config.js`でそれを有効にします。

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  compiler: {
    styledComponents: true,
  },
}
 
export default nextConfig

次に、`styled-components` APIを使用して、レンダリング中に生成されたすべてのCSSスタイルルールを収集するグローバルレジストリコンポーネントと、それらのルールを返す関数を作成します。その後、`useServerInsertedHTML`フックを使用して、レジストリで収集されたスタイルをルートレイアウトの`` HTMLタグに挿入します。

lib/registry.tsx
'use client'
 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
 
export default function StyledComponentsRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://react.dokyumento.jp/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())
 
  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement()
    styledComponentsStyleSheet.instance.clearTag()
    return <>{styles}</>
  })
 
  if (typeof window !== 'undefined') return <>{children}</>
 
  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  )
}

ルートレイアウトの`children`をスタイルレジストリコンポーネントでラップします。

app/layout.tsx
import StyledComponentsRegistry from './lib/registry'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  )
}

外部スタイルシート

外部パッケージによって公開されたスタイルシートは、併置されたコンポーネントを含む`app`ディレクトリ内のどこでもインポートできます。

app/layout.tsx
import 'bootstrap/dist/css/bootstrap.css'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className="container">{children}</body>
    </html>
  )
}

外部スタイルシートは、npmパッケージから直接インポートするか、ダウンロードしてコードベースに配置する必要があります。``を使用することはできません。

APIリファレンス

このページで言及されている機能について詳しくは、APIリファレンスをご覧ください。