我正在尝试从this教程中重新创建浮动标签。
当我从教程添加此代码时(在教程中检查15:00)
.form-group input:focus + .label-name .content-name,
.form-group input:valid + .label-name .content-name {
transform: translateY(-120%);
font-size: 14px;
color: #5fa8d3;
}
标签失去浮动效果。检查下面的图像。标签的此状态仅在输入为focused
时才有效。但是出于某些奇怪的原因,这是默认状态。仅当在上面的代码中添加.form-group input:valid + .label-name .content-name
时才会发生这种情况。
这是我的完整代码
.form-group {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.form-group input {
width: 100%;
height: 100%;
color: #595f6e;
background-color: #fbf9fa;
padding-top: 20px;
border: none;
}
.form-group input:focus {
background-color: #fbf9fa;
}
.form-group label {
position: absolute;
bottom: -10px;
left: 0%;
width: 100%;
height: 120%;
pointer-events: none;
border-bottom: 1px solid black;
}
.form-group label::after {
content: "";
position: absolute;
left: 0px;
bottom: -1px;
height: 100%;
width: 100%;
border-bottom: 3px solid #5fa8d3;
transform: translateX(-100%);
transition: transform 0.5s ease;
}
.content-name {
position: absolute;
bottom: 5px;
left: 0px;
transition: all 0.5s ease;
}
.form-group input:focus + .label-name .content-name,
.form-group input:valid + .label-name .content-name {
transform: translateY(-120%);
font-size: 14px;
color: #5fa8d3;
}
html
<div class="form-group">
<input type="text" class="form-control" name='input-name'>
<label for="input-name" class='label-name'>
<span class='content-name'>Enter your name</span>
</label>
</div>
答案 0 :(得分:2)
我还没有所有的CSS,但是通过您提供的摘录,我可以通过将required
属性添加到input
来使其正常工作。
当您没有required
属性时,输入始终为“有效”。因此,始终使用具有:valid
的css选择器。
请参见以下代码段中的演示:
.form-group {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.form-group input {
width: 100%;
height: 100%;
color: #595f6e;
background-color: #fbf9fa;
padding-top: 20px;
border: none;
}
.form-group input:focus {
background-color: #fbf9fa;
}
.form-group label {
position: absolute;
bottom: -10px;
left: 0%;
width: 100%;
height: 120%;
pointer-events: none;
border-bottom: 1px solid black;
}
.form-group label::after {
content: "";
position: absolute;
left: 0px;
bottom: -1px;
height: 100%;
width: 100%;
border-bottom: 3px solid #5fa8d3;
transform: translateX(-100%);
transition: transform 0.5s ease;
}
.content-name {
position: absolute;
bottom: 5px;
left: 0px;
transition: all 0.5s ease;
}
.form-group input:focus + .label-name .content-name,
.form-group input:valid + .label-name .content-name {
transform: translateY(-120%);
font-size: 14px;
color: #5fa8d3;
}
<div class="form-group">
<input type="text" class="form-control" name='input-name' required>
<label for="input-name" class='label-name'>
<span class='content-name'>Enter your name</span>
</label>
</div>