当输入类型设置为电子邮件时,带有 CSS 的浮动标签不起作用

Floating Labels with CSS not working when input type is set to Email

当我们输入标签浮动到顶部的内容时,我有一个输入文本框。当输入类型为 "text" 时它工作正常,但如果输入文本框设置为类型 "Email" 它停止工作,我需要一个解决方案来使其工作。

.relPos {
  position: relative;
}

.upLabel {
  position: absolute;
  top: 0px;
  left: 0;
  transition: .3s;
  pointer-events: none;
}

.upInputs input {
  box-shadow: none;
}

.upInputs input:focus~.upLabel,
.upInputs input:valid~.upLabel {
  top: -15px;
  border: none;
}
<br>
<div class="relPos upInputs">
  <input type="text" required>
  <label class="upLabel">Type="Text"</label>
</div>
<br>
<div class="relPos upInputs">
  <input type="email" required>
  <label class="upLabel">Type="Email"</label>
</div>

<br>

:valid 只会在输入有效时触发,因此您需要一封电子邮件 (xxx@yyy.zz) 才能正常工作。相反,您可以考虑使用 :placeholder-shown ref 并使用空占位符:

.relPos {
  position: relative;
}

.upLabel {
  position: absolute;
  top: 0px;
  left: 0;
  transition: .3s;
  pointer-events: none;
}

.upInputs input {
  box-shadow: none;
}

.upInputs input:focus~.upLabel,
.upInputs input:not(:placeholder-shown)~.upLabel {
  top: -15px;
  border: none;
}
<br>
<div class="relPos upInputs">
  <input type="text" required placeholder=" ">
  <label class="upLabel">Type="Text"</label>
</div>
<br>
<div class="relPos upInputs">
  <input type="email" required placeholder=" ">
  <label class="upLabel">Type="Email"</label>
</div>

<br>

:valid

来说明问题

.relPos {
  position: relative;
}

.upLabel {
  position: absolute;
  top: 0px;
  left: 0;
  transition: .3s;
  pointer-events: none;
}

.upInputs input {
  box-shadow: none;
}

.upInputs input:valid~.upLabel {
  top: -15px;
  border: none;
}
<div class="relPos upInputs">
  <input type="email" required value="not an email">
  <label class="upLabel">Type="Email"</label>
</div>
<br>
<div class="relPos upInputs">
  <input type="email" required value="example@email.com">
  <label class="upLabel">Type="Email"</label>
</div>