:focus-within

Avatar of Chris Coyier
Chris Coyier on (Updated on )

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

The :focus-within pseudo-selector in CSS is a bit unusual, although well-named and rather intuitive. It selects an element if that element contains any children that have :focus.

form:focus-within {
  background: lightyellow;
}

Which works like this…

<!-- this form will be selected -->
<form action="#">

  <!-- when this input is in focus -->
  <input type="text">

</form>

I said “unusual” because it’s not common in CSS to be able to select a parent element based on the existence or state of child elements. Sure is useful though!

Here’s an example form to try it on:

Note that example uses :focus-within on the entire form and on interior input-wrapping <div>s.

Any way that a child element can become focused will trigger :focus-within. For example, if an element has a tab-index or contenteditable attribute, then it is a focusable element, and will work. It also doesn’t matter how the element became focused. It could be clicked or tapped, it could have been tabbed to or navigated to by some other means, or even focused through JavaScript, like…

document.querySelector("input").focus();

Browser Support

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

ChromeFirefoxIEEdgeSafari
6052No7910.1

Mobile / Tablet

Android ChromeAndroid FirefoxAndroidiOS Safari
12612712610.3