[英]How to create multiple themes using Tailwind CSS?
查看 Tailwind CSS,您似乎需要在類中指定特定的 colors,如下所示:
<div class="bg-yellow-200 dark:bg-gray-800"></div>
但是,如果我想在我的 web 應用程序中提供 10 種不同的主題供用戶選擇怎么辦? 就像我可能有halloween
、 summer
、 winter
和party
等主題。
我知道使用常規 CSS 這很容易做到,如下所示:
[data-theme="halloween"] {
--color-bg: #000;
--color-body: #757981;
}
<body data-theme="halloween"></div>
然后使用 Javascript 我可以更改數據主題屬性,主題將會更改。
但是我怎么能用 Tailwind CSS 做到這一點呢? 我在文檔中找不到任何關於此的內容。
只是偶然發現了這個問題,因為我正在做幾年前已經做過的事情,但已經不記得了。 如果有人再次來到這里,也許這個答案可能會有所幫助。
在我們的案例中,我們正在構建一個應用於 3 個不同網站但明顯改變顏色和字體的主題,這似乎與問題作者的情況相同。
為此,可以使用順風預設。 我有一個tailwind.preset.js
,它基本上是默認的 tailwind 配置,包含所有基本顏色、間距等。對於每個主題,一個單獨的tailwind.<theme-name>.js
設置包含更改並基於自身預設。
示例tailwind.theme-one.js
:
module.exports = {
presets: [
require('./tailwind.preset.js')
],
theme: {
colors: {
# color changes go here
}
}
}
我們有一個 gulp 工作流設置,基本上只為每個主題配置渲染一次主 scss 文件。 在集成上,然后正在加載所需的主題文件。
我確實找到了使用 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>
有幾個插件支持定義多個 Tailwind 主題並在它們之間切換。 我特別喜歡thailwindcss-themer 插件,因為它允許您:
text-primary
)。 這使代碼保持獨立於插件(與其他插件相反,有時每個 CSS 類都需要特定的前綴)my-theme:font-bold
tw-colors正是這樣做的。
tailwind.config.js
const { createThemes } = require('tw-colors');
module.exports = {
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
plugins: [
createThemes({
halloween: {
'primary': 'orange',
'secondary': 'yellow',
},
summer: {
'primary': 'pink',
'secondary': 'red',
},
winter: {
'primary': 'blue',
'secondary': 'green',
},
party: {
'primary': 'steelblue',
'secondary': 'darkblue',
},
})
],
};
在 class 中使用這樣的主題:
<html class='theme-halloween'>
...
</html>
或者使用數據屬性:
<html data-theme='halloween'>
...
</html>
可以使用一些切換按鈕或任何您喜歡的方式動態切換主題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.