:focus-within

Matches an element if it or any of its descendants have focus. Useful for form container styling.

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.

:focus-within Browser Support

Widely available Since 2019 89% global usage

This feature is well established and works across many devices and browser versions. It has been available across browsers since 2019.

Safe to use without fallbacks.

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.

ESC