🦋

Next.jsプロジェクトにTailwind CSSで抽象的なテーマカラー名のCSSクラスを設定する

2022/04/10に公開

Primary Color や Secondary Color を設定したい

Tailwind CSS には、22 種類のカラープリセットが用意されて、さらに種類ごとに 10 の濃淡に分かれています。
その合計は、なんと 220 色!(v3.0.23 現在)

色が豊富で便利ですが、redblueなどのように具体的な色名ではなく、primarysecondaryのように抽象的な色名で指定したい場合もあります。
今回は公式ドキュメントを見ながら、どのように設定するのかみていきます。

公式ドキュメントを読んで見る

公式には、以下の内容が記されています。

But when you do need to customize your palette, you can configure your colors under the colors key in the theme section of your tailwind.config.js file:

「パレットをカスタムするにはtailwind.config.jstheme.colorsプロパティで設定できます」的なことが書いてあります。

また、こんな便利なことも書かれています。

By default, these colors will be made available everywhere in the framework where you use colors, like the text color utilities, border color utilities, background color utilities, and more.

「設定した色は、テキストカラーやボーダーカラー、バックグラウンドカラーなどフレームワークのどこでも使えるよ」的なことが書いています。

つまりは、tailwind.config.jstheme.colorsプロパティに色を追加すると、bg-<custom-color>text-<custom-color>みたいなことができると解釈できますね…?!

では、実際にためして見ましょう。

https://tailwindcss.com/docs/customizing-colors

tailwind.config.jsをいじる

公式によると以下のように書くと良いらしい。

tailwind.config.js
module.exports = {
  theme: {
    colors: {
      primary: '#5c6ac4',
      secondary: '#ecc94b',
    }
  }
}

これでも良いのだが、私はcolorsプロパティの設定を外部モジュールに切り分けて管理したいので、別の方法で設定します。

colorsプロパティを外部モジュールに切り分ける

簡単ではありますが、ディレクトリ構成としては以下の様になります。

root/
├ src/
│   ├ styles/colors.ts
│   └ pages/index.tsx
└ tailwind.config.js

まずは、tailwind.config.jsから書いていきます。

colorsプロパティに外部モジュールを設定してあげるだけです。

tailwind.config.js
const { resolve } = require('path');
const colorsPath = resolve(__dirname, 'src/styles/colors.ts');
const colors = require(colorsPath);

module.exports = {
  // ...
  theme: {
    colors: colors,
  },
  plugins: [],
  // ...
};

次に、色設定ファイルを作成します。
今回はsrc/stylesディレクトリ内にcolors.tsファイルを作成し、その中にテーマカラーを設定していきます。

src/styles/colors.ts
module.exports = {
  primary: '#FFFF00', // 黄色
  secondary: '#FF00FF',// ピンク
};

テーマカラーが反映されているか確かめる

適当にbg-primarytext-secondaryclassNameに追加してみます。

すると背景黄色で文字ピンクの「Hello World」が表示されているのが確認できるとお思います。

src/pages/index.tsx
import React from 'react';

const Index = () => {
  return <div className={'bg-primary text-secondary'}>Hello World</div>
}

export default Index;

🎉🎉🎉

Thanks

https://tailwindcss.com/docs/customizing-colors

GitHubで編集を提案

Discussion