:focus-within CSS Pseudo Class
Description
The :focus-within pseudo-class in CSS is used to target an element when it or any of its descendants has received focus. This makes it particularly useful for styling parent containers based on the focus state of child elements, which cannot be achieved using the standard :focus pseudo-class alone. Essentially, it allows developers to apply visual cues to a grouping element, such as a form or a menu, when any interactive descendant is active, improving accessibility and user experience.
For example, consider a form field wrapped in a div. You can highlight the entire container when a user focuses on any input inside it:
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
</div>
.form-group:focus-within {
border: 2px solid blue;
background-color: #f0f8ff;
}
In this example, the border and background color of the .form-group container change whenever the user focuses on the <input> element inside it. This approach is particularly useful for improving the visual clarity of complex forms or interactive components.
The :focus-within pseudo-class works seamlessly with other selectors and can be combined with states like :hover or :active. It is also helpful when styling navigation menus, such as highlighting a li element when any link inside it receives focus, which is valuable for keyboard navigation.
Because :focus-within applies to parent elements of the focused target, it can reduce the need for JavaScript in certain UI interactions, making your code simpler and more performant. Additionally, it works with any focusable descendant, including input, select, textarea, and button.
Syntax
:focus-within {
/* ... */
}
Example
Browser Support
The following information will show you the current browser support for the CSS :focus-within pseudo class. Hover over a browser icon to see the version that first introduced support for this CSS psuedo class.
This psuedo class is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 31st December 2025
