仅使用CSS在Input上创建浮动标签?

时间:2019-05-22 07:33:35

标签: html css css3

我只想使用CSS在输入上创建浮动标签,但将其作为修饰符类使用,以免影响原始输入,并显示和隐藏占位符文本。

因此,我需要保持相同的HTML结构。

我找到了示例,但它们似乎都说输入必须在标签之前?

使用我的标记是否可以仅使用CSS创建标记?

<div class="test-field test-field--light">
  <label for="a" class="test-field__label">Input label</label>
  <input class="test-field__input" id="a" placeholder="Placeholder text" type="text" value="">
</div>

这是我的笔: enter image description here

以下是我需要的示例: https://codepen.io/anon/pen/XwVrwY

谢谢

1 个答案:

答案 0 :(得分:1)

您应该更改HTML的至少一行,因为没有“上一个同级”选择器。因此,我们无法选择test-field__label上的test-field__input事件。

请检查代码:

body {
  padding: 15px 35px;
  background: #f5f5f5;
}

.test-field {
    clear: both;
    margin-bottom: 20px;
    position: relative;
}

.test-field--light .test-field__input {
    background-color: #ffffff;
    border-color: #eee;
}

.test-field__input {
    font-size: 0.875em;
    line-height: 1;
    -moz-appearance: none;
    -webkit-appearance: none;
    background-color: #f5f5f5;
    border: 2px solid #eee;
    border-radius: 4px;
    color: grey;
    height: calc((40 / 14) * 1em);
    line-height: 1;
    outline: 0;
    padding: 0 8px;
    vertical-align: top;
    width: 100%;
}

// FOCUS
.test-field__input:focus, 
.test-field__input ~ input:checked:focus {
    border-color: #5d7199;
}

// DISABLED
.test-field--disabled .test-field__input {
    background-color: #e8e8e3;
    cursor: not-allowed;
}

.test-field--disabled .test-field__flag, .test-field--disabled .test-field__label {
    color: #d0d0cb;
}

// ERROR
.test-field--error .test-field__input, .test-field--error .test-field__selection .atc-field__input {
    border-color: #ff4436;
    color: #ff4436;
}

// FLOATING LABEL

.test-field--floating .test-field-input {
  position: relative;
  margin-bottom: 1.5rem;
}
.test-field__label {
  position: absolute;
  top: 0;
  padding: 7px 0 0 13px;
  transition: all 200ms;
  opacity: 0.5;
}

.test-field__input:focus + .test-field__label,
.test-field--floating .test-field__input:valid + .test-field__label {
  font-size: 75%;
  transform: translate3d(0, -100%, 0);
  opacity: 1;
}
<div class="test-field test-field--light">
  <input class="test-field__input" id="a" type="text" value="">
  <label for="a" class="test-field__label">Input label</label>
</div>

<div class="test-field test-field--floating">
  <input class="test-field__input" id="b"  type="text" value="" required>
  <label for="a" class="test-field__label">Input label</label>
</div>