结构:
<div class="form-item">
<input type="text" id="username" required />
<span class="bar"></span>
<label for="username">User Name</label>
</div>
样式:
.form-item {
position: relative;
width: 300px;
margin: 100px auto;
input {
width: 93.5%;
font-size: 18px;
border: none;
border-bottom: 2px solid #ccc;
}
input:focus {
// input 聚焦时只显示下划线
outline: none;
width: 93.5%;
border-bottom: 2px solid #ccc;
}
input:focus ~ .bar {
position: absolute;
left: 0;
bottom: 0;
width: 94.7%;
height: 2px;
background-color: yellow;
}
label {
position: absolute;
top: 0;
left: 0;
color: #ccc;
}
// input:valid 表单验证
input:focus ~ label,
input:valid ~ label {
position: absolute;
top: -18px;
left: 0;
color: #ccc;
transition: 0.4s ease;
}
}
效果: