底部浮动标签有效,但顶部没有

时间:2016-09-13 23:34:35

标签: html css forms css3 labels

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

这是我的代码,我制作了两个表单来向您展示两个标签之间的区别。
请检查并确定我的问题:)谢谢!

.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>

1 个答案:

答案 0 :(得分:0)

+ CSS选择器仅适用于相邻元素,因为您的选择器为.field + .label,而label中的field-container2位于input之前,根据该CSS规则不会被选中。