:focus-within
Widely availableSince 202097% of users
Matches an element if it or any of its descendants have focus. Useful for form container styling.
What's modern
From web-features, MDN's browser data and our snippets, checked dailyModernIn every major browser since January 2020. Widely available since July 2022.
See how modern your own CSS is.Check your CSS →
Quick example
form:focus-within { border: 2px solid blue; }
form:focus-within input { background: #f0f8ff; }Examples
Highlight a form when any input has focus
form:focus-within {
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.3);
}
/* Form glows when user focuses any input inside */Use :focus-within to show which form is active without adding classes via JavaScript.
Show labels when related input is focused
.field:focus-within label {
color: blue;
font-weight: bold;
}
/* Label highlights when input gets focus */Highlight related labels by nesting them in a parent that matches :focus-within.
Expand menu on focus
.dropdown:focus-within .menu {
max-height: 500px;
visibility: visible;
}
/* Menu stays open while focus is inside */Keep a dropdown menu visible when focus is on any child element.
Common pitfalls
- :focus-within vs :focus:focus-within matches if any descendant has focus, not the element itself. If you want to style only the focused element, use :focus instead.
- Loses focus on mouse leave:focus-within stays active while focus is inside the container. When you blur the input, :focus-within no longer matches. Combine with :hover to keep menus open on hover too.
:focus-within browser support
BaselineWidely availableThis feature is well established and works across many devices and browser versions. It has been available across browsers since 2020.Safe to use without fallbacks.
Usage97%of people can use this3% use a browser without it.
Browsers
60+
52+
10.1+
79+Mobile
60+Android
52+Android
10.3+iOS