December 9, 2019
Echobind Team
Tags:
The :focus-within CSS pseudo-class represents an element that has received focus or contains an element that has received focus. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus. (This includes descendants in shadow trees.) — MDN Docs
Or, succinctly:
It selects an element if that element contains any children that have :focus. — Chris Coyier
There are many creative use-cases for this pseudo-class; a common use-case is applying focus styles to the parent of a focusable element. Here are a couple of examples:
With that class handy, we can target the parent to display styles whenever one of its children is focused.
Click to see the full source code here.
When either the input or button is focused, the parent “container” element displays an animated box-shadow to give visual focus.
2. List of items with focusable content
Here’s an example to demonstrate the usefulness of this particular pseudo-class. A list of forms is displayed, and when an input field or button is focused, the individual list item is highlighted with a different-colored background to indicate focus.
Providing location context to your users is considerate, pragmatic and delightful.
This is how it’s achieved in the code:
Click to see the full source code here.
For effect, we can take it a step further. When any element within the form is focused, the button color also changes. This is done by targeting the button when the list item detects any focused children.
Note: There is no support for IE or Edge.
Join the Echobind Team - we're always looking to partner with excellent talent to bring great ideas to life.
Check our Careers today.