html - 如何使用 Tailwind CSS 创建多个主题?
问题描述
查看 Tailwind CSS,您似乎需要在类中指定特定颜色,如下所示:
<div class="bg-yellow-200 dark:bg-gray-800"></div>
但是,如果我想提供 10 种不同的主题供用户在我的 Web 应用程序中选择怎么办?就像我可能有主题halloween
和summer
和winter
等等party
。
我知道使用常规 CSS 很容易做到这一点:
[data-theme="halloween"] {
--color-bg: #000;
--color-body: #757981;
}
<body data-theme="halloween"></div>
然后使用 Javascript 我可以更改 data-theme 属性,并且主题也会更改。
但是我怎么能用 Tailwind 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>
推荐阅读
- vue.js - 用户在 vuejs 中的 FullCalendar 切换事件
- c++ - 枚举可变参数模板参数包
- xml - 如何在 XML 中处理 # 和多个 tns:?
- reactjs - 单击主体上的侦听器(某些 div 除外)
- sql - HIVE:使用原始表中特定列的 n 值创建一个包含 n 列的新表
- r - 如何将日期转换为最近的周末(星期六)
- vbscript - 带小时和分钟的 VBS 时间范围
- java - Android Studio - gradle 警告:所有 com.android.support 库必须使用完全相同的版本规范
- botframework - 如何将 BotAuthentication 注入控制器
- excel - 删除前导或尾随空格,但不删除 Excel 上文本或单词之间的空格