: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 树中的后代元素。)

尝试一下

这个选择器非常有用,举个常见的例子,当用户聚焦于一个 <input> 字段时,可以用它来突出显示整个 <form> 容器。

语法

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

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:focus-within

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见