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:
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 atabindex
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 thediv
’s background will also be#aaa
.This will remove the need for JavaScript that is often used to achieve this effect.