基于深色模式的顺风颜色

问题描述 投票:0回答:3

有什么方法可以在 tailwind 配置中定义不同的颜色,以便在没有

dark
选择器的情况下应用深色模式?

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

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

} 

我喜欢只使用red-100

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

    

tailwind-css
3个回答
36
投票
您可以在 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; } }
然后在您的

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", }, }
现在,如果您在文档根颜色上设置深色类别,则会自动更改


4
投票

这里是我编写的顺风插件(tw-colors),它正是您所需要的。

const { createThemes } = require('tw-colors'); module.exports = { // ...your tailwind config plugins: [ createThemes({ 'light': { 'red': { '100': '#880808', '200': '...', } }, 'dark': { 'red': { '100': 'red', '200': '...', } }, }) ], };
将主题应用于父元素

<div class={someCondition ? 'theme-light' : 'theme-dark'}> ... </div>
您可以像往常一样使用您的颜色。

<button class='bg-red-100'>...</div>
如果 

theme-light

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

    


1
投票
您可以利用的一个技巧是

提取为组件

在你的顺风样式表中

@tailwind base; @tailwind components; @tailwind utilities; @layer components { .red-bg { @apply bg-red-100 dark:bg-red-dark-100; } }
然后您可以将其用作

<div class="red-bg"></div>
并且它按预期工作。然而,最好的做法是在“重新使用样式”中使用其他方法,因为将此技巧扩展到项目中使用的所有颜色会很不方便。
    

© www.soinside.com 2019 - 2024. All rights reserved.