:focus-within

:focus-within 是一个CSS 伪类 ,表示一个元素获得焦点,或,该元素的后代元素获得焦点。换句话说,元素自身或者它的某个后代匹配 :focus 伪类。(shadow DOM 树中的后代也包括在内)

/* 当 <div> 的某个后代获得焦点时,匹配 <div> */
div:focus-within {
  background: cyan;
}

该选择器非常实用。举个通俗的例子:表单中的某个 <input> 字段获得焦点时,整个表单的 <form> 元素都可被高亮。

语法

:focus-within

Example

此例子中,当表单某个文本输入框获得焦点后,表单会被设置颜色样式。

HTML

<p>试试在这个表单中输入点什么。</p>

<form>
  <label for="given_name">Given Name:</label>
  <input id="given_name" type="text">
  <br>
  <label for="family_name">Family Name:</label>
  <input id="family_name" type="text">
</form>

CSS

form {
  border: 1px solid;
  color: gray;
  padding: 4px;
}

form:focus-within {
  background: #ff8;
  color: black;
}

input {
  margin: 4px;
}

结果

规范

规范 状态 备注
Selectors Level 4
:focus-within
Working Draft Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
:focus-withinChrome Full support 60Edge Full support 79Firefox Full support 52IE No support NoOpera Full support 47Safari Full support 10.1WebView Android Full support 60Chrome Android Full support 60Firefox Android Full support 52Opera Android Full support 44Safari iOS Full support 10.3Samsung Internet Android Full support 8.0

Legend

Full support  
Full support
No support  
No support

参见