首页 > 解决方案 > CSS:根据相邻兄弟更改样式

问题描述

我正在研究一个纯 CSS 解决方案,用于在输入中显示占位符文本,一旦聚焦,它也成为上面的标签,如许多 Google Material 框架中所见。

我有默认状态和焦点状态工作,但是在用户输入一个值后,我需要更改 <label> 样式并且无法弄清楚(如果它甚至可能)读取相邻输入以及它是否是 input:valid改变 <label> 的样式

由于遵循 Bootstrap 4,我无法修改 HTML 的层次结构

<div class="form-group">
    <label class="placeholder" for="exampleInputEmail1">Email Address</label>
    <input type="email" class="form-control" id="exampleInputEmail1">
</div>

如您所见, <input> 和 <label> 处于同一级别,有没有办法根据 input:valid 伪类更改 <label> ?

您可以在这里看到一个半工作示例:https ://codepen.io/FritzAPI/pen/ERMvvR

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400,500,700');
@import url('https://fonts.googleapis.com/icon?family=Material+Icons');

/* Fritz Material Placeholder Start */
.form-group:focus-within label:not(.form-check-label):not(.custom-control-label) {
    color: #2196F3;
}
label:not(.form-check-label):not(.custom-control-label) {
    margin-bottom: 0px;
    color: rgba(0,0,0,0.54);
}
.form-group:focus-within label.placeholder:not(.form-check-label):not(.custom-control-label) {
    color: #2196F3;
    top: 0px;
    font-size: 14px;
    transition: all 0.3s cubic-bezier(0, 0, 0.2, 1);
}
label.placeholder:not(.form-check-label):not(.custom-control-label) {
    margin-bottom: 0px;
    color: rgba(0,0,0,0.38);
    position: relative;
    top: 28px;
    font-size: 16px;
    margin-top: -2px;
    transition: all 0.3s cubic-bezier(0, 0, 0.2, 1);
    z-index: -1;
}
/* Fritz Material End */

body {
  text-align: left;
  text-align: start;
  background-color: white;
  color: rgba(0, 0, 0, 0.87);
  font-family: Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1.428572;
  margin: 0;
}

/* Forms, Input Group Start */
.form-control:focus, .form-control-file:focus, .custom-select:focus {
  background-color: transparent;
  border-color: #2196f3;
  box-shadow: inset 0 -2px 0 -1px #2196f3;
  outline: 0;
}
.form-control, .form-control-file, .custom-select {
    height: 2.0rem;
    line-height: 1.428572;
    padding: 0.410714rem 0 0.348214rem;
    background-clip: padding-box;
    background-color: transparent;
    background-image: none;
    border-color: rgba(0, 0, 0, 0.42);
    border-radius: 0;
    border-style: solid;
    border-width: 0 0 1px;
    box-shadow: none;
    color: rgba(0, 0, 0, 0.87);
    display: block;
    width: 100%;
}
/* Forms, Input Group End */
<div class="form-group">
    <label class="placeholder" for="exampleInputEmail1">Email Address</label>
    <input type="email" class="form-control" id="exampleInputEmail1">
</div>

在 <input> 有一个值后,我需要标签在失去焦点时保持在输入之上。

标签: csscss-selectorsbootstrap-4

解决方案


推荐阅读