LoginSignup
0
0

【TailwindCSS】カスタムテーマをダークモードとして設定する

Posted at

TailwindCssには標準でダークモードに対応していて、設定を行うと、下記のようにhtml要素のクラス名にdarkを設定した場合に、dark:bg-blackを有効にすることができます。

<!-- Dark mode not enabled -->
<html>
<body>
  <!-- Will be white -->
  <div class="bg-white dark:bg-black">
    <!-- ... -->
  </div>
</body>
</html>

<!-- Dark mode enabled -->
<html class="dark">
<body>
  <!-- Will be black -->
  <div class="bg-white dark:bg-black">
    <!-- ... -->
  </div>
</body>
</html>

ただ、このままだと外部ライブラリが用意するテーマを使用したときに、暗めのテーマをダークモードとして認識しません。

具体的に、下図のようなDaisyUIが用意するSynthwaveのようなテーマを使いたいとします。

image.png

DaisyUIの公式の設定に従って設定すると、

<html data-theme="synthwave"></html>
<body>
  <div class="bg-white dark:bg-black"> <!-- dark:bg-black not worked
    <!-- ... -->
  </div>
</body>
</html>

とすることで、synthwaveというテーマを使用することができますが、dark:bg-black は有効になりません。

どうすればsynthwaveのような暗めのカスタムテーマをダークモードとしてTailwindCSSに認識させることができるのでしょうか?

カスタムテーマをダークモードとして設定する

TailwindCSSの公式ドキュメントに以下の記述があります。

image.png

これに従い、次のようにtailwind.config.jsを設定します。

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: ['class', '[data-theme="synthwave"]'],
  // ...
}

'[data-theme="synthwave"]'を追加することで、先のほど例において

<html data-theme="synthwave">
<body>
  <div class="bg-white dark:bg-black"> <!-- dark:bg-black now working
    <!-- ... -->
  </div>
</body>
</html>

カスタムテーマに対しダークモードとしてTailwindCssに認識させることができます。

以上です。

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