You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 16:05:09