【问题标题】:Is it possible to select the nearest css selector, or parent是否可以选择最近的css选择器或父级
【发布时间】:2019-08-09 11:17:14
【问题描述】:

抱歉,标题用了笼统的措辞,无论如何,我有一些简单的 HTML,如下所示:

<div class="block flex-1 mx-4 relative w-1/2">
    <div class="form-group label-floating">
        <label class="control-label">Password</label>
        <input class="form-control" placeholder="" type="password">
        <span class="material-input"></span>
    </div>
</div>

现在,每当有人点击输入时,我都会像这样缩小标签大小:

使用以下css:

&.label-floating {

    &:focus-within {
        & > .control-label {
            top: 10px;
            font-size: 11px;
            line-height: 1.07143;
        }
    }
}

现在,我的问题是,如果输入不为空并且用户离开输入,标签将恢复正常大小。所以我尝试过这样的事情:

使用以下 css:

&.label-floating {

    &:focus-within {
        & > .control-label {
            top: 10px;
            font-size: 11px;
            line-height: 1.07143;
        }
    }

    & input:not(:empty){
        & .control-label {
            top: 10px;
            font-size: 11px;
            line-height: 1.07143;
        }
        & < .control-label {
            top: 10px;
            font-size: 11px;
            line-height: 1.07143;
        }
    }
}

无济于事,所以,我的问题是,有没有办法用纯 css 实现我想要的?

编辑:请有人编辑 OP 以嵌入图像。

用纯 css 更新:

.form-group {
  margin-bottom: 1.5rem;
  position: relative;
}

.form-group > .control-label {
  color: #888da8;
}

.form-group.label-floating:focus-within > .control-label {
  top: 10px;
  font-size: 11px;
  line-height: 1.07143;
}

.form-group.label-floating input:not(:empty) .control-label {
  top: 10px;
  font-size: 11px;
  line-height: 1.07143;
}

【问题讨论】:

  • 欢迎来到 StackOverflow!看起来您正在使用某种 CSS 预处理器,例如 LESS 或 SASS。您可能希望添加适当的问题标签。
  • @HarryCutts SASS/LESS 即使使用也与问题无关,这是一个纯 CSS 问题
  • 为不懂 sass/less 的人更新了纯 css。
  • /* active state */ input:focus ~ label, input:valid ~ label { top:-20px; font-size:14px; color:#5264AE; } codepen.io/chrisoncode/pen/IdGKH
  • @KunalAwasthi 如果用户输入了无效的电子邮件,它将不起作用,因为状态将是“无效”,即使我想要一些可选的,这也不会要求我所有的输入都是“必需的” ? codepen.io/thedeepnate/pen/PLBmWa

标签: html css css-selectors placeholder


【解决方案1】:

您不能在不检查内容是否有效的情况下定位包含值的输入。但是,您可以使用迂回的方式来检查输入是否具有 no 值。

您的输入具有placeholder 属性。 CSS 选择器:placeholder-shown 将定位显示占位符的输入;也就是说,指定了占位符属性且不为空的输入。

因此,您必须设置空输入标签的样式。

.form-control:placeholder-shown ~ .control-label {
  font-size: 20px;
  color: red;
}

.label-floating:focus-within > .control-label,
.form-control ~ .control-label {
  font-size: 11px;
    color: blue;
}
<div class="form-group label-floating">
    <input class="form-control" placeholder="" type="password">
    <label class="control-label">Password</label>
</div>

请注意,:placeholder-shown 未在 IE/Edge 中实现,尽管是 highly requested;但是,有 polyfills 可用。

【讨论】:

  • 我已经接受了这个答案,您能否在底部写一个说明,说明占位符解决方法在 IE/edge 中不起作用,以防将来有人看到这个答案?
猜你喜欢
  • 2022-12-20
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 2012-02-04
  • 2015-11-04
  • 1970-01-01
  • 2013-04-05
相关资源
最近更新 更多