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

如何使用纯HTML和CSS实现附图所示的输入框内标签效果?

实现输入框内部浮动标签(纯HTML+CSS)

没问题,这种输入框的**浮动标签(Floating Label)**效果完全可以用纯HTML和CSS实现,下面是完整的代码示例,和你要的效果一致:

HTML 结构

<div class="input-container">
  <input type="text" id="username" required>
  <label for="username">用户名</label>
</div>

<div class="input-container">
  <input type="email" id="email" required>
  <label for="email">邮箱地址</label>
</div>

CSS 样式

/* 全局基础样式(可选,用于美化) */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: Arial, sans-serif;
}

body {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 40px;
  background-color: #f5f5f5;
}

/* 输入框容器:核心是相对定位 */
.input-container {
  position: relative;
  width: 300px;
}

/* 输入框样式 */
.input-container input {
  width: 100%;
  padding: 12px 10px 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  background-color: white;
  /* 留出顶部空间给标签 */
  padding-top: 18px;
  transition: border-color 0.3s ease;
}

/* 输入框聚焦时的边框样式 */
.input-container input:focus {
  outline: none;
  border-color: #2196f3;
}

/* 标签样式:绝对定位在输入框内部 */
.input-container label {
  position: absolute;
  top: 16px;
  left: 12px;
  font-size: 16px;
  color: #999;
  pointer-events: none; /* 点击标签时直接触发输入框聚焦 */
  transition: all 0.3s ease; /* 所有变化都加过渡动画 */
}

/* 输入框聚焦或内容有效时,标签浮动上移 */
.input-container input:focus + label,
.input-container input:valid + label {
  top: 4px;
  font-size: 12px;
  color: #2196f3;
}

关键原理说明

  • 容器相对定位:让标签的绝对定位基于容器,不会乱跑
  • pointer-events: none:确保点击标签区域时直接触发输入框的聚焦事件
  • :focus + :valid 伪类:focus处理输入框激活状态,:valid确保输入内容后标签保持上移状态(依赖input的required属性)
  • 过渡动画:让标签的位置、字体大小变化更平滑自然

你可以根据自己的需求调整颜色、字体大小、输入框尺寸这些参数,完全适配你的附图效果~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:03:16