[CSS3] Tailwindcss 夜间模式

在 tailwindcss 里面,要开启夜间模式,非常非常简单,只需要使用 dark: 变体即可,dark: 后面跟上原子类,表示夜间模式下面需要应用的原子类。

例如:

<body class="bg-gray-100 dark:bg-gray-900"></body>

在上面的代码中,如果是白天模式,body 这个标签会应用 bg-gray-100 这个原子类,如果是夜间模式,那么就会应用bg-gray-900这个原子类。

因此要支持夜间模式,其实主要的工作就是针对一个元素编写两套不同的原子类,一套适用于白天模式,另外一套适用于夜间模式。

例如:

<body class="bg-gray-100 dark:bg-gray-900">
    <div class="container mx-auto px-4 py-12">
      <div
        class="bg-white dark:bg-gray-800 shadow-lg rounded-lg max-w-md mx-auto p-8"
      >
        <h2 class="text-2xl font-bold text-gray-800 dark:text-white">
          Card Title
        </h2>
        <p class="mt-4 text-gray-600 dark:text-gray-300">
          This is a sample card with a title, paragraph, and a button. The card
          will automatically switch between light and dark modes based on your
          system settings.
        </p>
        <button
          class="mt-6 inline-flex items-center justify-center px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 border border-transparent rounded-md shadow-sm dark:bg-yellow-400 dark:hover:bg-yellow-500 dark:text-gray-900"
        >
          Click me
        </button>
      </div>
    </div>
  </body>

在上面的代码中,我们就针对了不同的元素都设置了两套原子类样式,主要一般设置夜间模式的时候,只会去修改元素的颜色相关的信息,其他内容一般是不会动的。

接下来我们需要在配置文件里main配置夜间模式,tailwindcss 支持两套配置方案:

  • 跟随系统

只需要在配置文件中将 darkMode 配置项配置为 media 即可

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: 'media',
  // ...
}
  • 手动切换

需要将配置文件中的 darkMode 配置为 class

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: 'class',
  // ...
}

之后通过切换 html 根元素的 dark 样式类来达到切换夜间模式的效果。也就是说,如果 html 根元素挂载了 dark 这个样式类,那么就是夜间模式,如果没有挂载 dark 这个样式类,就不是夜间模式。

posted @ 2025-03-08 04:50  Zhentiw  阅读(57)  评论(0)    收藏  举报