The :focus-within pseudo-class matches an element when it or a descendant has focus. It can style a surrounding group without script. It does not move focus, create a label, or replace the visible focus indicator on the actual control.
CSS :focus-within: mark the active field group
When to use it
A payment search form groups an amount field with a currency selector. When either control receives focus, a modest wrapper border shows which group is active. The input and select keep their own focus-visible outline so a keyboard user can identify the precise control, not just the group. The base wrapper border remains present when no control is focused. Test mouse clicks, Tab movement between the two controls, an error state, forced colors, and a browser that does not apply the enhancement. Do not rely on focus-within to style a server error: a failed submission needs error text and an accessible association even after focus moves elsewhere. Nested dialogs and popovers can change where focus resides; verify the group does not remain visually active after an overlay takes focus. A wrapper highlight is optional context, not the sole focus signal.
.payment-filter { border: 2px solid #8aa2b1; padding: .75rem; }
.payment-filter:focus-within { border-color: #1c5e87; }
.payment-filter :focus-visible { outline: 3px solid #1c5e87; outline-offset: 2px; }Cost and verification
Selector matching and a border-color change are inexpensive. The main maintenance cost is reconciling focus, invalid, disabled, and error styles so the wrapper does not imply success when a control is invalid. Avoid a border-width change on focus because it can shift the form layout. Check contrast of both wrapper and control indicators against the actual background. The descendant focus ring remains essential, especially in a group with more than one field. CSS cannot tell whether the form value passed server validation. Keep label text, hint text, and error text in the document where they remain available without this visual enhancement.
Common Mistakes
- Do not remove the focused control's own indicator.
- Do not treat focus-within as validation feedback.
- Do not change border width and shift the form on every Tab move.
