Using :focus to style outer div?

Other posters have already explained why the :focus pseudo class is insufficient, but finally there is a CSS-based standard solution.

CSS Selectors Level 4 defines a new pseudo class:

:focus-within

From MDN:

The :focus-within CSS pseudo-class matches any element that the :focus pseudo-class matches or that has a descendant that the :focus pseudo-class matches. (This includes descendants in shadow trees.)

So now with the :focus-within pseudo class - styling the outer div when the textarea gets clicked becomes trivial.

.box:focus-within {
    border: thin solid black;
}

.box {
    width: 300px;
    height: 300px;
    border: 5px dashed red;
}

.box:focus-within {
    border: 5px solid green;
}
<p>The outer box border changes when the textarea gets focus.</p>
<div class="box">
    <textarea rows="10" cols="25"></textarea>
</div>

Codepen demo

NB: Browser Support : Chrome (60+), Firefox and Safari


DIV elements can get focus if set the tabindex attribute. Here is the working example.

#focus-example > .extra {
  display: none;
}
#focus-example:focus > .extra {
  display: block;
}
<div id="focus-example" tabindex="0">
  <div>Focus me!</div>
  <div class="extra">Hooray!</div>
</div>

For more information about focus and blur, you can check out this article.

Update: And here is another example using focus to create a menu.

#toggleMenu:focus {
  outline: none;
}
button:focus + .menu {
  display: block;
}
.menu {
  display: none;
}
.menu:focus {
  display: none;
}
<div id="toggleMenu" tabindex="0">
  <button type="button">Menu</button>
  <ul class="menu" tabindex="1">
    <li>Home</li>
    <li>About Me</li>
    <li>Contacts</li>
  </ul>
</div>