gpt4 book ai didi

html - 是否可以选择最近的 css 选择器或父级

转载 作者:可可西里 更新时间:2023-11-01 13:41:51 25 4
gpt4 key购买 nike

抱歉标题措辞一般,无论如何,我有一些简单的 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>

现在,只要有人点击输入,我就会像这样缩小标签大小:

Password field with shrunk label

使用以下 CSS:

&.label-floating {

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

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

Password field with text entered and full-size label

使用以下 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;
}

最佳答案

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

您的输入有一个 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可用。

关于html - 是否可以选择最近的 css 选择器或父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55232358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com