:focus-within CSS Pseudo Class
Description
The :focus-within
pseudo-class is a CSS selector that targets an element when any of its descendants receive focus. This means that when a user interacts with an element or its child elements, such as clicking or using the keyboard to focus on an input field within that element, the parent element will also be affected by the CSS rules defined for :focus-within
.
It is particularly useful for creating interactive and accessible user interfaces. For example, you can use :focus-within
to style a form container when an input field within it is focused, providing visual feedback to the user and improving the user experience. Here's a simple example:
.container:focus-within {
border: 2px solid #007bff; /* Add a border when any descendant element is focused */
background-color: #f0f0f0; /* Change the background color */
}
In this example, when an input field inside the
.container
is focused, the container itself will receive a border and change its background color, making it clear to the user which part of the form they are interacting with.
Syntax
:focus-within { /* ... */ }
Example
<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>
form {
border: 1px solid;
color: gray;
padding: 4px;
}
form:focus-within {
background: #ff8;
color: black;
}
input {
margin: 4px;
}
Browser Support
The following table will show you the current browser support for the CSS :focus-within
pseudo class.
Desktop | |||||
79 | 60 | 52 | 47 | 10.1 |
Tablets / Mobile | |||||
60 | 52 | 44 | 10.3 | 8 | 60 |
Last updated by CSSPortal on: 1st October 2023