从TailWind 3.1开始,你可以编写plugin或使用相同的任意变体.它不完全是组属性,但使用了相同的概念-因此,它可以包含您想要的任何类名,而不是.group
,但使用.group
会很方便
// tailwind.config.js
const plugin = require('tailwindcss/plugin')
/** @type {import('tailwindcss').Config} */
module.exports = {
theme: {
extend: {
// ...
},
},
plugins: [
plugin(function({ addVariant }) {
addVariant('group-with-foo', '.group.foo &') // custom CSS
addVariant('group-no-foo', '.group:not(.foo) &')
})
],
}
addVarinat
函数是创造新变种的原因.第一个参数变量名称应唯一.第二-任何有效的作为字符串的css(或应该返回字符串的函数).
&
符号指向具有此自定义变量的元素.您的插件应该有&
或以@
开头的符号,否则它将无效.
<a class="group">
<span class="group-with-foo:bg-red-500">
Parent has NOT `foo` class therefore I'm NOT red
</span>
<span class="group-no-foo:bg-red-500">
Parent has NOT `foo` class but it doesn't matter (it has `group` though)
</span>
</a>
<hr>
<a class="group foo">
<span class="group-with-foo:bg-red-500">
It is red because parent has BOTH `group` and `foo` class
</span>
<span class="group-no-foo:bg-red-500">
Parent has `foo` class therefore I'm not red
</span>
</a>
如果您需要使用任意变量,您需要传递相同的css作为第二个参数,但您应该使用_
来代替空格.如果您的类有_
符号,则必须将其转义为\_
<a class="group">
<span class="[.group.foo_&]:bg-red-500">
It is red because parent has BOTH `group` and `foo` class
</span>
<span class="[.group:not(.foo)_&]:bg-red-500">
Parent has `foo` class therefore I'm not red
</span>
</a>
DEMO个