The
:focus-withinpseudo 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
divwith the class.containerreceives focus (it can in this case as it has atabindexof 0, this is purely for example purposes), it will have a background colour of#aaa.But it will also have a background colour of
#aaaif 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.