:focus-within

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:

See the Pen Simple Responsive Form with :focus-within by Chris Coyier (@chriscoyier) on CodePen.

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

ChromeOperaFirefoxIEEdgeSafari
604752NoNo10.1

Mobile / Tablet

iOS SafariOpera MobileOpera MiniAndroidAndroid ChromeAndroid Firefox
10.3NoNoNo6155
This comment thread is closed. If you have important information to share, please contact us.
icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag