如何在TailwindCSS中使用peer伪类检测同级元素是否存在?
在TailwindCSS中通过自定义Peer选择器识别同级label元素
1. 配置自定义选择器
在你的tailwind.config.js里扩展自定义选择器,用来定位同级存在label的input:
/** @type {import('tailwindcss').Config} */ module.exports = { content: ["./src/**/*.{html,js,jsx}"], theme: { extend: { selectors: { // 匹配所有同级存在label的input 'input-with-sibling-label': 'input:has(+ label), input:has(~ label)' } } }, plugins: [] }
2. 编写HTML结构并应用样式
不需要给label加额外的peer-[label]类,直接在input上用自定义选择器设置全圆角,同时保留默认的first:/last:圆角规则:
<!-- 有同级label的情况 --> <div class="flex flex-col"> <label for="email">Email</label> <input id="email" class="input-with-sibling-label:rounded-3xl first:rounded-t-3xl last:rounded-b-3xl bg-green-400" /> </div> <!-- 无同级label的情况,自动应用first/last圆角 --> <div class="flex flex-col"> <input id="name" class="first:rounded-t-3xl last:rounded-b-3xl bg-green-400" /> </div>
3. 无需配置的简化写法(Tailwind v3.2+)
如果不想修改配置文件,直接用Tailwind原生支持的:has()伪类写内联选择器:
<div class="flex flex-col"> <label for="email">Email</label> <input id="email" class="[:has(+ label), :has(~ label)]:rounded-3xl first:rounded-t-3xl last:rounded-b-3xl bg-green-400" /> </div>
注意事项
- 你原来代码里的
hmtlFor是拼写错误,原生HTML应写for,React中写htmlFor;className是React语法,原生HTML要用class。 :has()伪类需要现代浏览器支持,若要兼容旧版浏览器,建议使用配置自定义选择器的方式。
内容的提问来源于stack exchange,提问作者wongx
相关产品推荐
相关产品推荐

