說明:此系列文章是個人對Tailwind CSS官方文檔的翻譯,不是很嚴謹,請諒解。
添加工具類
盡管tailwind 提供了一系列很全面的開箱即用的工具類,但是難免還是會有那種添加自定義類的情況。
想要確定一種擴展框架的最佳方式是一件讓人挺頭大的事,于是這里很貼心地列舉了幾種添加自定義工具類的最佳實踐,你可以選自己用的最順手的一種。
直接在 CSS 文件莫問添加自定義工具類
/* 千萬不要寫在這里 */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* 記住,得寫在這里 */
.retote-0{
transform: retote(0deg);
}
.retote-90{
transform:retote(90deg);
}
.retote-180 {
transform: retote(180deg);
}
.retote-270 {
transform:retote(270deg);
}
由于在CSS中聲明順序很重要,得確保新的工具類要寫在CSS文件最底下,這樣就避免了一些特異性問題。千萬不要把自定義工具類寫在 CSS 文件頂上。
如果項目中使用的事postcss-import
或者Less, Sass 或 Stylus 這種預處理器的話,最好是把自定義的工具類寫在一個獨立的文件里面,然后把它引入。
/* 使用 postcss-import 的情況 */
@important "tailwindcss/base";
@important "tailwindcss/components";
@important "tailwindcss/utilities";
@important "./custom-utilities.scss"; /* 注意這句?? */
/* 使用 Sass 或者 Less 的情況 */
@tailwind base;
@tailwind components;
@tailwind utilities;
@important "./custom-utilities"; /* 注意這句?? */
生成響應變體
如果你在tailwind.config.js
文件中定義了斷點,而且想要給基于這些斷點的自定義工具類創建相應變體的話,就可以在@responsive
指令中將工具類進行包裹。
@tailwind base;
@tailwind components;
@tailwind utilities;
@responsive {
.retote-0 {
transform: retote(0deg);
}
.retote-90 {
transform: retote(90deg);
}
.retote-180 {
transform: retote(180deg);
}
.retote-270 {
transform: retote(270deg);
}
}
Tailwind 會自動給咱自定義工具類生成前綴版本,就可以在不同的斷點處根據相應的條件應用這些樣式了。
<!-- 默認的是旋轉180度,如果是在中等及以上大小的屏幕上就撤銷旋轉的樣式 -->
<div calss="retote-180 md:retote-0"></div>
創建偽類變體
要是想給自定義工具類創建偽類變體的話,就直接在@variants
指令里進行包裹:
@tailwind base;
@tailwind components;
@tailwind utilities;
@variants hover, focus {
.rotate-0 {
transform: rotate(0deg);
}
.rotate-90 {
transform: rotate(90deg);
}
.rotate-180 {
transform: rotate(180deg);
}
.rotate-270 {
transform: rotate(270deg);
}
}
這樣,Tailwind 會自動給每個自定義工具類生成前綴版本,就可以在不用的狀態下給元素應用這些樣式。
<div class="retote-0 hover:retote-90"></div>
偽類變體的生成順序跟你寫在@variants
指令種中的順序是一致的,所以你如果想用某個偽類的優先級比另一個高的話,就得確保這個得寫在優先級低的偽類的后面。
/* Focus 的優先級比 hover 的高 */
@variants hover, focus {
.retote-0 {
transform: retote(0deg);
}
/* ... */
}
要是你想同時生成自定義工具類的響應式變體和偽類變體的話呢,就把@variants
指令包在 @responsive
指令里面就好了:
@tailwind base;
@tailwind components;
@tailwind utilities;
@responsive {
@variants hover, focus {
.rotate-0 {
transform: rotate(0deg);
}
.rotate-90 {
transform: rotate(90deg);
}
.rotate-180 {
transform: rotate(180deg);
}
.rotate-270 {
transform: rotate(270deg);
}
}
}
使用插件
除了直接在CSS 文件里面添加之外,你也可以寫插件來給 Tailwind 添加工具類。
//tailwind.config.js
const plugin = require('tailwindcss/plugin')
module.exports = {
plugin: [
plugin(function({ addUtilities }){
const newUtilities = {
'.retote-0': {
transform: 'retote(0deg)',
},
'.retote-90': {
transform: 'retote(90deg)',
},
'retote-180': {
transform: 'retote(180deg)',
},
'retote-270': {
transform: 'retote(270deg)'
},
}
addUtilities(newUtilities, ['responsive', 'hover'])
})
]
}
如果你想把自己的自定義工具類作為庫發布、或者想在多個項目之間共享使用的話,用插件就是個很好的選擇了。