0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

next.js 13 でカスタムカラーを設定しよう!

Last updated at Posted at 2025-04-05

動機

next.jsのアプリ開発でTailwindのデフォルト設定されているカラーパレット以外で、カスタムで用意したいと思った。

Tailwindの設定ファイルtailwind.config.jsのtheme.extend.colorsに設定を記述することでデフォルトのカラーパレットを追加することができる手法を試してみたが、適用することができなかった。

ちなみに、適用できない件に関して以下のことは試してみた。

・tailwind.config.js がプロジェクトのルートディレクトリに正しく配置されているか確認
・プロジェクトのルートに postcss.config.js ファイルがあることを確認
・CSSファイルのインポート確認
・開発サーバーの完全な再起動
・キャッシュの削除

他の手法を模索

app/global.cssにCSS 変数を直接使用して、以下のように定義すると

:root {
  --color-custom-red: #FF5154;
  --color-custom-red-light: #FF6567;
  --color-custom-purple: #B900FF;
}

次のようにコンポーネント内で使用できる。

<div style={{ backgroundColor: 'var(--color-custom-red)' }} className="w-20 h-20"></div>

だがこれだと記述が長くなり、可読性が悪い。
そこで!!
Tailwind の @apply ディレクティブを使ってカスタムクラスを作成すると
使いやすく汎用性アップする(classNameにそのまま指定できる)

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

:root {
  --color-custom-red: #FF5154;
  --color-custom-red-light: #FF6567;
  --color-custom-purple: #B900FF;
}

/* ここで、ユーティリティクラスを設定 */
@layer utilities {
  .bg-custom-red {
    background-color: var(--color-custom-red);
  }
  .bg-custom-red-light {
    background-color: var(--color-custom-red-light);
  }
  .bg-custom-purple {
    background-color: var(--color-custom-purple);
  }
}

この方法なら、通常の Tailwind クラスと同じように使える

<div className="w-20 h-20 bg-custom-red"></div>

記述も短くなり、プロジェクト内で汎用がしやすくなった!ハッピー!!!

やったことをまとめると

  1. global.css: ルート要素にカスタムカラー変数を定義
  2. global.css: @layer utilities を使って Tailwind のユーティリティクラスとしてカスタムカラーを設定
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?