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

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

该选择器非常有用,举个通俗的例子:当用户在表单中某个<input> 域上获得焦点,会高亮整个表单。

语法

:focus-within

Example

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

HTML

<p>Try typing into this form.</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;
}

Result

规范

Specification Status Comment
Selectors Level 4
:focus-within
Working Draft Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung Internet
Basic supportChrome Full support 60Edge No support No
Notes
No support No
Notes
Notes This feature is not implemented. See the enhancement request.
Firefox Full support 52IE No support NoOpera Full support 47Safari Full support 10.1WebView Android Full support 60Chrome Android Full support 60Edge Mobile No support No
Notes
No support No
Notes
Notes This feature is not implemented. See the enhancement request.
Firefox Android Full support 52Opera Android Full support 47Safari iOS Full support 10.3Samsung Internet Android No support No

Legend

Full support  
Full support
No support  
No support
See implementation notes.
See implementation notes.

参见

文档标签和贡献者

此页面的贡献者: Ritr, nDos, qdlaoyao, 15207108156
最后编辑者: Ritr,