CSS 中的 :focus-within 伪类选择器选择一个元素,如果它包含已接收焦点的元素 (:focus)。
例如,如果要突出显示或聚焦整个表单,则当焦点设置在任何输入字段上时,请使用伪类 :focus-within。
语法
:focus-within {
/* ... */
}
CSS :focus-within 示例
以下示例演示了 :focus-within 伪类的用法。当焦点设置在输入字段上时,该输入字段的标签将高亮显示。
<html>
<head>
<style>
label {
display: block;
font-size: 20px;
color: black;
width: 500px;
}
input[type="text"] {
padding: 10px 16px;
font-size: 16px;
color: black;
background-color: #fff;
border: 1px solid #597183;
border-radius: 8px;
margin-top: 5px;
width: 500px;
transition: all 0.3s ease;
}
input[type="text"]:focus {
background-color: lightyellow;
}
label:focus-within {
font-size: 25px;
color: red;
}
</style>
</head>
<body>
<form>
<label>
Full Name
<input type="text">
</label>
</form>
</body>
</html>
以下示例演示了 :focus-within 伪类的用法。当焦点设置在下拉列表上时,标签的背景和边框会发生变化。
<html>
<head>
<style>
label {
display: grid;
font-size: 18px;
color: black;
width: 400px;
}
select {
padding: 10px 16px;
font-size: 16px;
color: black;
background-color: #fff;
border: 1px solid #597183;
border-radius: 8px;
margin-top: 25px;
width: 300px;
transition: all 0.3s ease;
}
select:focus {
background-color: rgb(173, 233, 209);
}
label:focus-within {
background-color: coral;
border: 2px dashed black;
}
</style>
</head>
<body>
<form>
<label>
Ice cream Flavors:
<select name="flavor">
<option>Cookie dough</option>
<option>Pistachio</option>
<option>Cookies & Cream</option>
<option>Cotton Candy</option>
<option>Lemon & Raspberry Sorbet</option>
</select>
</label>
</form>
</label>
</form>
</body>
</html>