使用 Tailwind CSS 构建多色模板的正确方法是什么?

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

在 Tailwind CSS 中为模板创建自定义配色方案非常简单。您只需修改

tailwind.config.js
,添加您的自定义调色板,然后像 Tailwind 的普通类一样使用它。例如
bg-brand-500

    theme: {
        extend: {
            colors: {
                brand: {
                    '50': '#B0ECEC',
                    '100': '#A0E8E8',
                    '200': '#7FE1E1',
                    '300': '#5ED9D9',
                    '400': '#3DD1D1',
                    '500': '#2CB9B9',
                    '600': '#218C8C',
                    '700': '#165E5E',
                    '800': '#0C3131',
                    '900': '#010404'
                },
            }
        }
    }

现在我陷入了制作多色模板的困境。

我相信您在网络上都见过模板,例如您可以选择红色或蓝色,并且整个模板的配色方案会发生变化。

在 Tailwind 中如何做到这一点?

更新: 在其他 CSS 流派中,例如 SASS,您只需创建另一个颜色变量文件并使用常规

<link href='/path/to/red/variables.css' />
动态加载不同的文件。

colors tailwind-css
2个回答
4
投票

您可以使用 CSS 变量

在顺风配置中,您可以像以前一样创建品牌颜色,但您可以使用例如

50: 'var(--brand-50)'
,而不是十六进制颜色代码。然后在你的index.css中你可以将这些变量添加到基础层,例如:

@layer base {
    :root {
        --brand-50: #B0ECEC;
    } 
    .theme-red {
        --brand-50: #BB0000;
    }
}

现在,如果您将类

.theme-red
添加到您的正文中,
text-brand-50
将为红色。

在 Tailwind 实验室的这段视频中对此进行了全面解释。还解释了如何处理不透明度,尽管从 Tailwind 3.1 开始有一种更简单的方法来做到这一点

希望这有帮助。


0
投票

我编写了 tw-colors tailwind 插件,使多主题更容易处理。

  1. 创建您的主题
   const { createThemes } = require('tw-colors');

   module.exports = {
      content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
      plugins: [
         createThemes({
            light: { 
                brand: {
                    '50': '#B0ECEC',
                    '100': '#A0E8E8',
                    '200': '#7FE1E1',
                    '300': '#5ED9D9',
                    '400': '#3DD1D1',
                    '500': '#2CB9B9',
                    '600': '#218C8C',
                    '700': '#165E5E',
                    '800': '#0C3131',
                    '900': '#010404'
                },
            },
            dark: { 
                brand: {
                    '50': '#321321',
                    '100': '#654654',
                    '200': '#987987',
                    '300': '#786541',
                    '400': '#aeeeee',
                    '500': '#786541',
                    '600': '#987987',
                    '700': '#165E5E',
                    '800': '#654654',
                    '900': '#321321'
                },
            }
         })
      ],
   };
  1. 使用您的主题
   <html class='theme-light'>
      <div class="bg-brand-500">...</div>
   </html>

然后您可以根据需要动态切换主题,例如使用 switch

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