首页 > 解决方案 > 如何使用 Tailwind CSS 创建多个主题?

问题描述

查看 Tailwind CSS,您似乎需要在类中指定特定颜色,如下所示:

<div class="bg-yellow-200 dark:bg-gray-800"></div>

但是,如果我想提供 10 种不同的主题供用户在我的 Web 应用程序中选择怎么办?就像我可能有主题halloweensummerwinter等等party

我知道使用常规 CSS 很容易做到这一点:

[data-theme="halloween"] {
    --color-bg: #000;
    --color-body: #757981;
}

<body data-theme="halloween"></div>

然后使用 Javascript 我可以更改 data-theme 属性,并且主题也会更改。

但是我怎么能用 Tailwind CSS 做到这一点呢?我在文档中找不到任何关于此的内容。

标签: htmlcsstailwind-css

解决方案


我确实找到了使用 CSS 变量的解决方案。

在您的 css 文件中,您可以像这样为每个主题定义样式

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

@layer base {
    [data-theme="default"] {
        --color-esther: 34, 39, 46;
        --color-maximus: 45, 51, 59;
        --color-linx: 55, 62, 71;
    }

    [data-theme="neon"] {
        --color-esther: 20, 61, 42;
        --color-maximus: 13, 82, 66;
        --color-linx: 20, 82, 11;
    }
}

然后在您的tailwind.config.js文件中,您可以像这样定义它们

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

function withOpacity(cssVariable) {
    return ({ opacityValue }) => {
        return `rgba(var(${cssVariable}), ${opacityValue})`
    }
}

module.exports = {
    //...

    theme: {
        colors: {
            'esther':       withOpacity('--color-esther'),
            'maximus':      withOpacity('--color-maximus'),
            'linx':         withOpacity('--color-linx'),
        },
    },
}

在您的 html 中,您可以像这样使用这些类:

<html lang="en" data-theme="default">
    <body class="bg-esther text-optimus cursor-default">

    </body>
</html>

推荐阅读