编辑:随着2.2+版的发布,它内置了对名为peer的兄弟选择器变体的支持(观看更新release)
此功能仅在即时模式下可用。
<label>
<input checked type="radio" name="option" id="option1" class="hidden peer" />
<div class="peer-checked:bg-red-600">option1</div>
</label>
对于 2.2 以下的版本:
您需要编写自己的插件来添加新变体。更多信息here
例如,将其命名为label-checked
tailwind.config.js
const plugin = require('tailwindcss/plugin');
module.exports = {
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {},
variants: {
extend: {
backgroundColor: ['label-checked'], // you need add new variant to a property you want to extend
},
},
plugins: [
plugin(({ addVariant, e }) => {
addVariant('label-checked', ({ modifySelectors, separator }) => {
modifySelectors(
({ className }) => {
const eClassName = e(`label-checked${separator}${className}`); // escape class
const yourSelector = 'input[type="radio"]'; // your input selector. Could be any
return `${yourSelector}:checked ~ .${eClassName}`; // ~ - CSS selector for siblings
}
)
})
}),
],
};
此配置应该适用于下一种情况(我们扩展了 backgroundColor,因此它应该适用于 bg-color 类):
1 - label 是包装器,它的文本应该包装在任何选择器中(在本例中为 div)
<label>
<input checked type="radio" name="option1" id="option1" class="hidden" />
<div class="label-checked:bg-red-600">option1</div>
</label>
2 - 标签 输入后
<input checked type="radio" name="option1" id="option1" class="hidden" />
<label for="option-1" class="label-checked:bg-red-600"></label>
演示 - https://play.tailwindcss.com/SEQ4NRpPV3