为什么浮动标签不适用于 css

Why is floating label not working with css

我正在尝试重新创建 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>

我没有你所有的 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>