Today I came across the a new CSS pseudo class that will be very handy for web developers who are styling focus states.
: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:
and the following CSS:
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
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
: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.