能否选择最近的CSS选择器或父级元素?

3
抱歉标题措辞过于笼统,无论如何,我有一些简单的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的方法来实现我想要的效果?

编辑:有人能否编辑原始帖子以嵌入图片?

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

1
欢迎来到StackOverflow!看起来你正在使用某种CSS预处理器,比如LESS或SASS。你可能想将适当的预处理器添加为问题标签。 - Harry Cutts
@HarryCutts 即使使用SASS/LESS,它们也与问题无关,这是一个纯CSS问题。 - Temani Afif
1
已更新为纯CSS,适用于不了解SASS/LESS的开发者。 - DumbAnswersForDumbQuestions
/* 活动状态 */ input:focus ~ label, input:valid ~ label { top:-20px; font-size:14px; color:#5264AE; } - Kunal Awasthi
@KunalAwasthi 如果用户输入无效的电子邮件,它将不起作用,因为状态将是“无效”,这是否需要让我所有的输入都是“必需的”,即使我想要一些可选的吗?https://codepen.io/thedeepnate/pen/PLBmWa - DumbAnswersForDumbQuestions
显示剩余2条评论
1个回答

1
你不能直接定位包含值的输入框,必须先检查其内容是否有效。但是你可以通过一种迂回的方式检查输入框是否为空。
你的输入框有一个“placeholder”属性。CSS选择器“:placeholder-shown”会定位显示占位符的输入框,也就是指已经指定了placeholder属性且不为空的输入框。
因此,你需要对空输入框的标签进行样式设置。

.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中未实现;但是,有polyfills可用。

1
我已经接受了答案,您能否在底部加上一条注释,说明占位符解决方法在IE/Edge中不起作用,以防将来有人看到这个答案? - DumbAnswersForDumbQuestions

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接