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

如何实现HTML输入框填充内容后Label保持在顶部?

问题

想要实现输入框填充数据后,label始终保持在输入框顶部的效果。目前已实现输入框聚焦时label上移,但尝试使用.txt_field input:focus ~ valid选择器后,标签仍与输入内容重叠,求可行解决方法。

现有代码

CSS

.txt_field input {
  width: 100%;
  padding: 0 5px;
  height: 40px;
  font-size: 16px;
  border: none;
  background: none;
  outline: none;
}

.txt_field label {
  position: absolute;
  top: 65%;
  left: 5px;
  color: #adadad;
  transform: translateY(-50%);
  font-size: 16px;
  pointer-events: none;
  transition: .3s;
}

.txt_field input:focus~label {
  top: 0px;
  color: #0170C1;
}

HTML

<div class="txt_field">
  <i class="fa fa-user"></i>
  <input type="text" class="textbox" id="username" placeholder="">
  <label>PhoneNumber/Email</label>
</div>

解决方法

你之前的选择器写法有误,.txt_field input:focus ~ valid是无效语法,正确做法是结合聚焦和内容状态的选择器,让输入框聚焦或有内容时,label固定在顶部。

方案1:适合必填输入框(用:valid)

  1. 给input添加required属性,输入内容后input会触发valid状态:
<input type="text" class="textbox" id="username" placeholder="" required>
  1. 修改CSS,新增:valid的规则:
.txt_field input:focus~label,
.txt_field input:valid~label {
  top: 0px;
  color: #0170C1;
}

说明:输入框为空时会处于invalid状态,label回到初始位置;如果需要允许输入框为空但只要有内容就保持label在顶部,用方案2。

方案2:支持空输入框(用:not(:placeholder-shown))

无需添加required,利用占位符的状态判断输入框是否有内容:

  1. 保持HTML不变(placeholder属性必须保留,即使值为空)
  2. 更新CSS选择器:
.txt_field input:focus~label,
.txt_field input:not(:placeholder-shown)~label {
  top: 0px;
  color: #0170C1;
}

说明:只要输入框内有内容,label就停留在顶部;清空内容后,label自动回到原位。

额外优化建议

为了避免label上移后和输入内容或边框重叠,给.txt_field设置相对定位,并给label添加背景色和内边距:

.txt_field {
  position: relative;
  margin: 30px 0;
  border-bottom: 2px solid #adadad; /* 可选,添加输入框底部边框 */
}

.txt_field label {
  /* 保留原有样式 */
  background: white; /* 匹配输入框背景色,防止文字重叠 */
  padding: 0 5px; /* 增加左右间距,避免贴边 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:15:36