TailwindCSS中无法选中input相邻兄弟标签?问题求助
问题:Input聚焦时无法修改相邻Span的背景色?
我的代码如下:
<input type='text' className='[&:focus + span]:bg-black border-b-2 border-dark10 px-24 py-16 focus:border-dark100' /> <span className='absolute left-0 top-1/2 ml-24 -translate-y-1/2 select-none text-16 font-normal text-dark40'> Test </span>
我使用了[&:focus + span]:bg-black,希望在input元素获得焦点时改变span的背景色,但该样式并未生效。请问我的错误在哪里?
解答
核心问题是Tailwind自定义选择器的写法逻辑错误,你写的[&:focus + span]:bg-black是把样式规则绑定在了input元素本身,而不是用来选中相邻的span元素,自然无法修改span的背景色。
给你两种可行的修正方案:
方案1:在span上绑定目标选择器
把选择器逻辑写到span的class里,让Tailwind正确识别要触发的条件:
<input type='text' className='border-b-2 border-dark10 px-24 py-16 focus:border-dark100' /> <span className='absolute left-0 top-1/2 ml-24 -translate-y-1/2 select-none text-16 font-normal text-dark40 [input:focus+&]:bg-black'> Test </span>
这里的[input:focus+&]会被编译成input:focus + span,直接选中input聚焦后的相邻span,给它设置黑色背景。
方案2:使用Tailwind的peer类(更推荐)
这是Tailwind官方提供的兄弟元素样式控制方案,更直观易懂:
<input type='text' className='peer border-b-2 border-dark10 px-24 py-16 focus:border-dark100' /> <span className='absolute left-0 top-1/2 ml-24 -translate-y-1/2 select-none text-16 font-normal text-dark40 peer-focus:bg-black'> Test </span>
给input加上peer标记,然后在span上用peer-focus:前缀,就能直接关联input的聚焦状态来控制span样式。
内容的提问来源于stack exchange,提问作者Ali Bahaari
相关产品推荐
相关产品推荐

