:focus-within
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
:focus-within
CSS 伪类表示当元素或其任意后代元素被聚焦时,将匹配该元素。换言之,它表示 :focus
伪类匹配到该元素自身或它的后代时,该伪类生效。(这也包括 shadow 树中的后代元素。)
尝试一下
语法
css
:focus-within {
/* ... */
}
示例
此例子中,当表单某个文本输入框获得焦点后,表单会被设置颜色样式。
HTML
html
<p>试试在这个表单中输入点什么。</p>
<form>
<label for="given_name">给定名称:</label>
<input id="given_name" type="text" />
<br />
<label for="family_name">家庭名称:</label>
<input id="family_name" type="text" />
</form>
CSS
css
form {
border: 1px solid;
color: gray;
padding: 4px;
}
form:focus-within {
background: #ff8;
color: black;
}
input {
margin: 4px;
}
结果
规范
Specification |
---|
Selectors Level 4 # the-focus-within-pseudo |
浏览器兼容性
BCD tables only load in the browser