说明:此系列文章是个人对Tailwind CSS官方文档的翻译,不是很严谨,请谅解。
伪类变体
用适合的伪类,可以定义元素hover、focus等情况的样式。
<button class="bg-teal-500 hover:bg-teal-600 focus:outline-none focus:shadow-outline ...">
Sign Up
</button>
支持的元素包括:hover, focus, active, disabled, visited, first-child, last-child, old-child, even-child, group-hover, group-focus, focus-widthin
注:当需要tailwind 不能支持的伪类时,可以自己对变体进行扩展(详见后面)
①First-child, Last-child, Old-child, Even-child 这样的变体应该将前缀加在子元素上而不是父元素
<!-- 前缀使用 first: last: old: even: -->
<div class="border rounded">
<div v-for="item in list" class="border-t first:border-t-0">
{{ item }}
</div>
</div>
②Group-hover, Group-focus 当悬停或焦点时间发生在父元素上时,可以使用子变体控制子元素的样式
用法:在父元素上添加 group 类,在子元素中使用group-hover: , group-focus: 前缀
<div calss="group bg-white hover:bg-blue-500...">
<p class="text-gray-900 group-hover:text-white...">New Project</p>
</div>
③Focus-within当焦点事件发生在某一子元素时,可以使用变体控制父元素样式
注意:在低于79.版本IE或Edge浏览器中不支持
用法:直接将focus-width: 前缀加在父元素上就好了
<form class="border-b-2 border-gray-400 focus-within:border-teal-500...">
<input class="..." placeholder="place input...">
<button class="...">
Sign up
</button>
</form>
④与响应式前缀搭配使用(sm, md,lg,xl)
用法:将响应式前缀放在变体前缀前面 如 sm:hover:
<button class="bg-orange-500 hover:bg-orange-600 md:bg-green-500 md:hover:bg-green-600">
Button
</button>
⑤可以在tailwind.config.js文件中定义是否一个工具类的变体可用
// tailwind.config.js
module.exports = {
// ...
variants: {
backgroundColor: ['responsive', 'hover', 'focus', 'active'],
opacity: ['responsive', 'hover', 'focus', 'disabled'],
textColor: ['responsive', 'hover', 'focus', 'group-focus'],
},
}
⑥为自定义工具类生成变体
在CSS中使用@variants
指令将其包裹
/* Input */
@variants group-hover,hover, focus {
.banana {
color: yellow;
}
}
/* Output 写上面那块就相当于写了下面这一堆了*/
.banana {
color: yellow;
}
.group:hover .group-hover\:banana {
color: yellow;
}
.hover\:banana:hover {
color: yellow;
}
.focus\:banana:focus {
color: yellow;
}
⑦当需要的伪类变体默认不支持时,可以通过写自定义变体插件创建自定义变体
例:添加disabled伪类变体的支持
//tailwind.config.js
const plugin = require('tailwindcss/plugin')
module.exports = {
plugin:[
plugin(function({ addVariant, e }){
addVariant('disabled', ({ modifySelectors, separator }) => {
modifySelectors(({ className }) => {
return `.${e(`disabled${separator}${className}`)}:disabled`
})
})
})
]
}