The :focus-within pseudo class

Today I came across a new CSS pseudo class that will be very handy for web developers who are styling focus states.

The :focus-within pseudo class becomes active when an element itself has focus or if any of its descendants does.

Take for example the following HTML code:

<div class="container" tabindex="0">
  <label for="text">Enter text</label>
  <input id="text" type="text" />
</div>

and the following CSS:

.container:focus-within {
  background-color: #aaa;
}

If the div with the class .container receives focus (it can in this case as it has a tabindex of 0, this is purely for example purposes), it will have a background colour of #aaa.

But it will also have a background colour of #aaa if any of its descendants have the focus. So if the <input> receives focus, then the div’s background will also be #aaa.

This will remove the need for JavaScript that is often used to achieve this effect.

The :focus-within pseudo class is currently supported in Firefox (since 52), Safari (since 10.1), and will come out from behind a flag in Chrome 60.

You can see it in action (on a supported browser) via this Codepen example.