Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Pseudo-classes

The :focus-within pseudo-class

Reference for the CSS :focus-within pseudo-class: style a container when any element inside it has focus, with syntax, form examples, usage notes and support.

The :focus-within pseudo-class matches an element when the element itself, or any of its descendants, has focus. It lets a parent react to what happens inside it, which CSS could not do before without JavaScript.

Typical uses: highlighting a whole form row when its input is focused, keeping a dropdown menu open while keyboard focus is inside it, or giving a search box a shared ring.

CSS
.field:focus-within {
  border-color: #2563eb;
}

Try it

Highlight the whole field group

Syntax

CSS
:focus-within { /* declarations */ }

No arguments; specificity (0,1,0). The match is dynamic: it turns on when focus enters the element's subtree and off when focus leaves.

Syntax and arguments

Part Description
:focus-within Matches an element if it, or a descendant (including in a shadow tree), matches :focus.
No arguments The pseudo-class is not functional.
Combining form:focus-within label, nav li:focus-within > ul.

Usage notes

  • It follows plain :focus, not :focus-visible. A mouse click inside the container also triggers it. For keyboard-only styling use :has(:focus-visible) on the container instead.
  • Keep a focus indicator on the field itself. Styling only the parent may not be enough for people who need a clear ring around the actual control.
  • Menus. Combine with :hover so a dropdown stays open for keyboard users: .menu:hover > ul, .menu:focus-within > ul { display: block; }.
  • Every ancestor matches. If the focused input is nested several levels deep, all of its ancestors match at once, including <body> and <html>.
  • Cheap to use. It is a plain selector; no scripting or classes are needed.

Browser support

Supported in all current browsers and Baseline widely available.