The :focus-within CSS pseudo-class matches any element that the :focus pseudo-class matches or that has a descendant that the :focus pseudo-class matches. (This includes descendants in shadow trees.)
/* Selects any <div> when one of its descendants is focused */
div:focus-within {
background: yellow;
}
This is useful, to take one example, for highlighting an entire form container when the user focuses on one of its form inputs.
Syntax
:focus-within
Examples
.name-container {
padding: 4px;
}
.name-container:focus-within {
background: yellow;
}
input {
margin: 4px;
}
<p>The div below will have a yellow background if
either input inside is focused.</p>
<div class="name-container">
<label for="given_name">
Given Name:
<input id="given_name" type="text">
</label>
<label for="family_name">
Family Name:
<input id="family_name" type="text">
</label>
</div>
Specifications
| Specification | Status | Comment |
|---|---|---|
| Selectors Level 4 The definition of ':focus-within' in that specification. |
Working Draft | Initial definition. |
Browser compatibility
| Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| Basic support | 60[1] | No support[2] | 52.0 (52.0)[3] | No support | 47 | 10.1 |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | 60[1] | 52.0 (52.0)[3] | No support | 47 | 10.3 |
[1] This feature was implemented in Chromium bug 617371.
[2] This feature is not implemented yet. See the related enhancement request.
[3] This feature was implemented in bug 1176997.
Document Tags and Contributors
Tags:
Contributors to this page:
mfluehr,
chrisdavidmills,
scottaohara,
rego,
tysongach,
DBaron,
jpmedley,
Sebastianz
Last updated by:
mfluehr,