如何使用 Tailwind 自定义深色模式颜色

How to have custom darkmode colors with Tailwind

提问人:K. Russell Smith 提问时间:2/9/2021 最后编辑:krishnaacharyaaK. Russell Smith 更新时间:3/13/2023 访问量:2891

问:

我正在尝试为我的项目设置 Tailwind(这是我第一次使用它),但不知道我应该如何定义深色和浅色主题的颜色;有没有办法做这样的事情:

@tailwind base;
@tailwind components;
@tailwind utilities;
@dark
{
   --red: #FFC8C8;
}
@light
{
   --red: #F00000;
}
module.exports = {
   darkMode: 'class',
   theme: {
      extend: {
         'red': 'var(--red)',
      }
   }
};

这是我试图做的事情的假设表示。不幸的是,我找到的 Tailwind 教程中没有一个解释如何做这样的事情。有没有办法使用 Tailwind 自定义暗模式调色板?谢谢。

CSS 用户界面 Tailwind-CSS

评论


答:

0赞 Anton S. 6/6/2022 #1

这里有一种方法可以做到这一点:

// tailwind.config.js

// only if you want to use (!)RGB values
function withOpacityValue(variable) {
  return ({ opacityValue }) => {
    if (opacityValue === undefined) {
      return `rgb(var(${variable}))`
    }
    return `rgb(var(${variable}) / ${opacityValue})`
  }
}

module.exports = {
  ...
  colors: {
    gray: {
      50: withOpacityValue('--gray-50'),
      ...
    }
  }
}

在你的顺风.css


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

:root {
  --gray-50: 192 178 131;
}

.dark {
  --gray-50: 220 208 192;
}

请注意,class 是您的主题的名称。 将成为您的默认主题。因此,您还可以定义其他主题。.dark:root.dark

我注意到的缺点之一(在我看来)是主题不会自动切换;用户将需要刷新页面。

参考: Tailwind -> Colors

4赞 krishnaacharyaa 6/7/2022 #2

最简单的方法是在 css 文件中给出自定义类名并赋予其浅色和深色属性。

tailwind.config.js

const colors = require("tailwindcss/colors");

module.exports = {
  mode: "jit",
  darkMode: "media",
  content: ["./src/**/*.{js,jsx}", "./public/index.html"],
  theme: {
    extend: {
      colors: {
        red: {
          dark: "#FFC8C8",
          light: "#F00000",
        },
    },
  },
  plugins: [],
};

索引.css

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

@layer base {
  .redcolor {
      @apply text-red-light dark:text-red-dark;
}

以这种方式应用。

 <div className=" p-4 redcolor">Hello</div>

灯光模式:enter image description here

深色模式:enter image description here