基于深色模式的 Tailwind 颜色

joh*_*yan 18 tailwind-css

有没有办法在顺风配置中定义不同的颜色,以便在没有选择器的情况下应用深色模式dark

目前我有一个像这样的对象:

const colors = {
 light: {
    red: {
     100: "#880808",
    ...
    }
  },
 dark: {
    red: {
     100: "red",
    ...
    }
  },

} 
Run Code Online (Sandbox Code Playgroud)

只想使用red-100并自动映射颜色(仅通过bg-red-100)而无需指定bg-red-100 dark:bg-red-dark-100

sad*_*adi 34

您可以在 CSS 文件中定义颜色,如下所示:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {

  :root {
    --color-primary: 247 147 34;
    --color-text: 33 33 33;
    --color-success: 0 200 81;
    --color-info: 51 181 229;
    --color-warn: 255 187 51;
    --color-error: 254 78 78;
  }

  :root[class~="dark"] {
    --color-primary: 247 147 34;
    --color-text: 33 33 33;
    --color-success: 0 200 81;
    --color-info: 51 181 229;
    --color-warn: 255 187 51;
    --color-error: 254 78 78;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: "class",
  theme: {
    colors: {
      primary: "rgb(var(--color-primary) / <alpha-value>)",
      text: "rgb(var(--color-text) / <alpha-value>)",
      success: "rgb(var(--color-success) / <alpha-value>)",
      info: "rgb(var(--color-info) / <alpha-value>)",
      warn: "rgb(var(--color-warn) / <alpha-value>)",
      error: "rgb(var(--color-error) / <alpha-value>)",
      transparent: "transparent",
      current: "currentColor",
    },
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您在文档根上设置深色类,颜色会自动更改

  • 不要忘记将 `&lt;alpha-value&gt;` 添加到您的主题中,否则您将失去对顺风不透明度类的支持。`主要:“rgb(var(--color-primary) / &lt;alpha-value&gt;)”`。您可以在 tailwind 文档中查看更多信息(https://tailwindcss.com/docs/customizing-colors) (3认同)

L.B*_*ndy 6

是一个顺风插件(tw-colors),它完全可以满足您的需求。

   const { createThemes } = require('tw-colors');

   module.exports = {
      // ...your tailwind config
      plugins: [
         createThemes({
            'light': { 
               'red': {
                  '100': '#880808',
                  '200': '...',
               }
            },
            'dark': { 
               'red': {
                  '100': 'red',
                  '200': '...',
               }
            },
         })
      ],
   };
Run Code Online (Sandbox Code Playgroud)

将主题应用到父元素上

<div class={someCondition ? 'theme-light' : 'theme-dark'}>  
  ...
</div>
Run Code Online (Sandbox Code Playgroud)

您可以像往常一样使用您的颜色。

<button class='bg-red-100'>...</div>
Run Code Online (Sandbox Code Playgroud)

如果theme-light应用于父元素,则背景颜色将为#880808,如果theme-dark应用于父元素,则背景颜色将为red