: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.

浏览器兼容性

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support60 No152 No4710.1
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support6060 No1524710.3 No

1. This feature is not implemented. See the enhancement request.

参见

文档标签和贡献者

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