【问题标题】:Floating label on bottom works but top doesn't底部的浮动标签有效,但顶部无效
【发布时间】:2017-01-21 16:05:08
【问题描述】:

所以我为表单制作了一个浮动标签,但问题是当我将标签放在顶部时它不会出现,但如果它在底部它会出现。我不知道问题到底出在哪里。

这是我的代码,我做了两个表格来告诉你两个标签之间的区别。
请检查并找出我的问题:) 谢谢!

.forms {
  width: 50%;
  padding: 50px;
}
.field-container {
  position: relative;
  line-height: 25px;
}
.field {
  display: block;
  width: 100%;
  padding: 5px 0;
  border: none;
  font-size: 14px;
  border-bottom: 1px solid #c5c5c5;
  margin: -5px 0;
}
.field input {
  color: blue;
}
.field:focus {
  outline: 0;
  color: #2580cd;
}
.floating-label {
  display: block;
  pointer-events: none;
  font-size: 10px;
  opacity: 0;
  background-color: white;
  -webkit-transition: 0.2s ease-in-out;
  transition: 0.2s ease-in-out;
}
.field:valid + .floating-label {
  opacity: 1;
  margin-top: -12px;
  color: #9e9e9e;
}
.field:focus + .floating-label {
  color: #2580cd;
}
.field:focus {
  border-bottom: 1px solid #2580cd;
}
/* THE OTHER ONE */

.field-container2 {
  position: relative;
  line-height: 25px;
}
.field2 {
  width: 100%;
  padding: 5px 0;
  border: none;
  font-size: 14px;
  border-bottom: 1px solid #c5c5c5;
  margin: -5px 0;
}
.field2:focus {
  outline: 0;
  color: #2580cd;
}
.floating-label2 {
  display: block;
  pointer-events: none;
  font-size: 10px;
  opacity: 0;
  background-color: white;
  -webkit-transition: 0.2s ease-in-out;
  transition: 0.2s ease-in-out;
}
.field2:valid + .floating-label2 {
  opacity: 1;
  color: #9e9e9e;
}
.field2:focus + .floating-label2 {
  color: #2580cd;
}
.field2:focus {
  border-bottom: 1px solid #2580cd;
}
<div class="forms">
  <form class="field-container">
    <input type="text" class="field" required placeholder="Label 1" />
    <label class="floating-label">Label 1</label>
  </form>

  <form class="field-container2">
    <label class="floating-label2">Label 2</label>
    <input type="text" class="field2" required placeholder="Label 2" />
  </form>
</div>

【问题讨论】:

    标签: html forms css labels


    【解决方案1】:

    + CSS 选择器仅适用于相邻元素,因为您的选择器是 .field + .label,并且您在 field-container2 中的 label 位于 input 之前,因此在该 CSS 规则下不会选择它。

    【讨论】:

    • 我按照您所说的方式更改了代码,但它仍然没有改变任何事情。它没有出现。
    • @user2522053 我想你误读了我的答案——我是说当标签高于输入时,你使用的 + 选择器将不起作用,这就是你拥有的原因那个问题。
    • @user2522053 没有 JavaScript,如果没有输入下方的标签,您将无法完成您想要的操作。大多数 CSS 框架目前在底部都有标签,因此它们可以使用 input:focus + label,然后根据需要转换标签
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多