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

登录表单中div下input元素的:focus样式不生效求助

解答

你的问题核心出在CSS选择器的使用上,另外明确下input:focus规则的生效逻辑:

  1. label样式不生效的原因
    你用的+是相邻兄弟选择器,它只能匹配紧跟在目标元素之后的同级元素。但你的HTML里label在input前面,这个选择器根本找不到对应的label,所以颜色变化的规则完全没触发。

  2. input:focus规则的说明
    你写的.login_form_fields input:focus语法是正确的,如果它没生效,要么是有优先级更高的CSS规则(比如带id的选择器、内联样式)覆盖了它,要么是你没正确触发input的焦点状态(比如没点击input框)。

修正方案

方案一:不调整HTML结构(推荐,适配现代浏览器)

使用CSS的:has()伪类,选中包含焦点input的div容器里的label:

/*Label Style*/
.login_form_fields:has(input:focus) label {
   color: blue;
}

/*Input Style*/
.login_form_fields input {
   border-radius: 2px;
   background: #fff;
   border: 1px solid #E3E3E3;
}

.login_form_fields input:focus {
   border: 1px solid blue;
}

方案二:兼容旧版浏览器

调整HTML结构,把input放在label前面,再用CSS调整布局(比如用flex反向排列),这样原来的+选择器就能生效:

<div class="login_form_fields uname" style="display: flex; flex-direction: column-reverse;">
   <input type="text" id="username" name="username" required>
   <label for="username">Username o Email:</label>
</div>
<div class="login_form_fields pswrd" style="display: flex; flex-direction: column-reverse;">
   <input type="password" id="password" name="password" required>
   <label for="password">Password:</label>
</div>

内容的提问来源于stack exchange,提问作者GorillaDev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:50:30