CSS pseudo-classPseudo-classes

:focus-within

Matches an element that either has focus itself or contains an element with focus. Lets you highlight an entire form or card.

On this page

Example

#
CSS
.search {
  border: 1px solid #3f3f46;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.search:focus-within {
  border-color: #a78bfa;
  box-shadow: 0 0 0 3px rgb(167 139 250 / 0.3);
}
Preview

Click the field. The whole container with the icon gets the outline, so the field itself can stay borderless.

Definition and usage

#

The :focus-within pseudo-class carries focus information up the tree. It matches the focused element and all of its ancestors. A form with :focus-within changes appearance the moment the user clicks any of its fields.

Itโ€™s a simple way to highlight a whole group: a form row, a search field with an icon, or a card with buttons. Effects like this used to require JavaScript.

It works with any kind of focus, including a mouse click. If you want to react only to keyboard focus, combine :has() with :focus-visible: .card:has(:focus-visible).

Syntax

#
Syntax
selector:focus-within { property: value; }

Common uses

#

Common uses in practice

#

.demo:focus-within

Click any field: the whole form lights up.
.demo:focus-within {
  background: rgb(124 58 237 / 0.2);
  outline: 2px solid #a78bfa;
}

label:focus-within

Only the label holding the active field lights up.
label:focus-within { color: #fbbf24; }

.demo:not(:focus-within)

The form stays dimmed until you click into one of its fields.
.demo:not(:focus-within) { opacity: 0.55; }

.demo:focus-within label:not(:focus-within)

Focus mode: while you type in one field, the other one fades.
.demo:focus-within label:not(:focus-within) { opacity: 0.4; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • When you hide a fieldโ€™s outline inside a larger component, show focus on the whole component through :focus-within. The indicator must stay visible.
  • A dropdown menu opened by :hover should also open through :focus-within. That way it can be used from the keyboard too.

Related entries

#

Spotted a mistake or missing an example? Write to us.