html - 当用户关注此时移动输入框的标签而不需要

标签 html css

当用户关注输入框时,我想在输入框上方移动一个标签。 There is an answer here ,但是,还是有一些区别的。我无法使用 required 因为我正在使用自定义验证。另外,输入框不止一个。

请参阅下面的代码。我一定是漏掉了一些愚蠢的东西。

.field {
  position: relative;
  padding-top: 10px;
}

.form label {
  position: absolute;
  top: 8px;
  left: 10px;
  pointer-events: none;
}

input:focus ~ label {
  top: -6px;
}
<form class="form">

  <div class="field">
    <label>Name</label>
    <input type="text">
  </div>

  <div class="field">
    <label>Age</label>
    <input type="text">
  </div>

</form>

最佳答案

要仅使用 css 创建它,您需要更改 inputlabel 的顺序,以便您可以使用 + 选择器。然后,当您关注 input

时,您可以在 label 上使用 transform: translate()

form {
  display: inline-block;
}
.field {
  padding-top: 10px;
  display: flex;
  flex-direction: column;
}
label {
  order: -1;
  padding-left: 5px;
  transition: all 0.3s ease-in;
  transform: translateY(20px);
  pointer-events: none;
}
input:focus + label {
  transform: translateY(-2px);
}
<form class="form">
  <div class="field">
    <input type="text">
    <label>Name</label>
  </div>

  <div class="field">
    <input type="text">
    <label>Age</label>
  </div>
</form>

关于html - 当用户关注此时移动输入框的标签而不需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43677055/

相关文章:

html - 在 HTML 中删除成功验证时的输入移位

javascript - 类似于 jqGrid 中的 treegrid

html - 修复元素,以便只有悬停在上面的元素会延伸?

html - 如何让较小的 div 堆叠到较大的 div 的右侧?

html - 关于 apache 或 weblogic 面试问题的图像

html - 跨浏览器 CSS 复选框问题

html - 为什么我的 bootstrap navbar css 不工作?

html - 如何在我的案例中设置类(class)

javascript - CSS 不会填充视口(viewport)

javascript - 如何获得 translate3d 的绝对值?