The :focus-within pseudo class

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:

Code language: HTML

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

and the following CSS:

Code language: 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.