如何在表单input获取焦点时更改对应label的文本颜色
问题根因
你使用的+相邻兄弟选择器只能匹配紧跟在当前元素之后的同级元素,但你的HTML结构里label放在input前面,所以input:focus + label无法选中对应label,样式不生效。
解决方案
方案1:用父元素:focus-within伪类(无需修改HTML,最便捷)
仅修改CSS即可适配现有结构:
input { background: transparent; position: relative; } label { color: black; } /* 父容器内input聚焦时,选中容器内的label */ .input-box:focus-within label { color: red !important; } /* 如果需要input聚焦时加边框,可以加下面这段 */ .input-box:focus-within input { border: 1px solid white; outline: none; }
你现有的HTML代码不需要做任何调整就能生效。
方案2:调整HTML元素顺序适配原有选择器
如果要保留你原来写的input:focus + label选择器,可以调整HTML里元素的顺序,再用flex的order属性调整视觉显示顺序:
<div class="input-box d-flex flex-column"> <input class="py-2 border-0 text-white" id="name" type="text" /> <!-- order:-1 让label视觉上显示在input前面 --> <label for="name" class="py-2" style="order: -1;">Your Name</label> </div>
内容的提问来源于stack exchange,提问作者Mr KnoX
相关产品推荐
相关产品推荐

