如果存在文本,则保持焦点样式

Bec*_*cky 2 css css-selectors

我有一个输入框。我在正常状态和焦点下定制它。

我的问题是,如果输入框中存在文本,如何保持焦点 CSS 样式?

.par input[type=sample]{
    width:75px;
    background-color: #000;
}
.par input[type=sample]:focus{
    width:50px;
    background-color: #FF0;
}
Run Code Online (Sandbox Code Playgroud)

Har*_*rry 6

没有纯 CSS 选择器可以根据文本框的内容直接选择文本框并设置其样式。但是,如果该字段是必填字段(即,您可以添加该required属性),则:valid可以使用伪选择器来识别文本框内部是否有任何文本类型,并根据它应用所需的样式。

input[type=text] {
  width: 75px;
  background-color: #000;
}
input[type=text]:focus,
input[type=text]:valid {
  width: 50px;
  background-color: #FF0;
}
Run Code Online (Sandbox Code Playgroud)
<input type="text" required />
<input type="text" required />
Run Code Online (Sandbox Code Playgroud)