
本教程详细介绍了如何使用 css 实现一个常见的 ui 模式:当用户在输入框中输入内容后,对应的标签(label)能从输入框内部平滑地移动到输入框上方并保持在该位置。文章将通过 `::placeholder-shown` 伪类、`position` 属性和相邻兄弟选择器 (`+`) 的结合运用,提供一套完整的 html 和 css 解决方案,确保标签的视觉效果和用户体验。
在现代 Web 表单设计中,一种流行的交互模式是“浮动标签”或“占位符标签”,即当输入框为空时,标签显示在输入框内部作为提示;一旦用户开始输入或输入框获得焦点,标签则平滑地移动到输入框上方。这种设计既节省了空间,又提供了清晰的用户指引。本文将详细讲解如何通过 CSS 实现这一效果,确保标签在输入框被填充后依然保持在顶部。
要实现这一效果,我们需要利用以下 CSS 特性:
首先,我们需要一个包含输入框和标签的父容器。确保 label 元素紧跟在 input 元素之后,因为我们将使用相邻兄弟选择器。
<div class="txt_field"> <i class="fa fa-user"></i> <input type="text" class="textbox" id="username" placeholder="请输入手机号/邮箱"> <label for="username">手机号/邮箱</label> </div>
注意事项:
接下来,我们将逐步构建 CSS 样式。
/* 容器样式 */
.txt_field {
position: relative; /* 确保子元素绝对定位的参照系 */
margin-bottom: 30px; /* 为浮动标签留出空间 */
border-bottom: 2px solid #adadad; /* 底部边框 */
}
/* 输入框样式 */
.txt_field input {
width: 100%;
padding: 0 5px;
height: 40px;
font-size: 16px;
border: none;
background: none;
outline: none; /* 移除默认焦点轮廓 */
z-index: 2; /* 确保输入框在标签之上 */
position: relative; /* 确保 z-index 生效 */
}
/* 标签样式 */
.txt_field label {
position: absolute;
top: 50%; /* 初始位置居中 */
left: 5px;
color: #adadad;
transform: translateY(-50%); /* 垂直居中 */
font-size: 16px;
pointer-events: none; /* 允许点击穿透到输入框 */
transition: .3s ease; /* 平滑过渡效果 */
z-index: 1; /* 确保标签在输入框之下 */
}
/* 输入框获得焦点或已填充时标签的样式 */
.txt_field input:focus + label,
.txt_field input:not(:placeholder-shown) + label {
top: -20px; /* 移动到输入框上方 */
font-size: 14px; /* 缩小字体 */
color: #0170C1; /* 改变颜色 */
transform: translateY(0%); /* 移除垂直居中 */
}
/* 隐藏原生占位符文本 */
.txt_field input::placeholder {
color: transparent;
}
/* 底部边框在焦点时的变化 */
.txt_field span::before {
content: '';
position: absolute;
top: 100%;
left: 0;
width: 0%;
height: 2px;
background: #0170C1;
transition: .3s;
}
.txt_field input:focus ~ span::before {
width: 100%;
}样式解析:
通过结合使用 position 属性、:focus 伪类、:not(:placeholder-shown) 伪类和相邻兄弟选择器 (+),我们成功实现了一个功能完善且用户体验良好的浮动标签效果。这种方法避免了 JavaScript 的复杂性,纯粹通过 CSS 实现了这一交互模式,提高了性能和可维护性。
关键点回顾:
以上就是实现输入框填充后标签保持在顶部的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号