:focus-within pseudo-selector - CSS

:focus-within is a helpful pseudo-selector in CSS.

It targets an element when it or any of its descendants receive focus.

If a user focuses on an input field or other form element within a container, the container can be styled based on the focus state.

This might not sound very clear, so I think a quick visual example is more helpful.

In the following example, when you focus on the inputs, you'll see the fieldset tag being highlighted:

This provides users with a clear visual cue that they are interacting with the multi-input field, even though it consists of multiple input elements - which could help if you want to create extra visual aids for a user for accessibility.

Here is the CSS code snippet so you can see how to apply it:

fieldset:focus-within {
  border-color: rgb(0, 128, 255);
  box-shadow: 0 0 0 2px rgba(0, 128, 255, 0.5);
  font-weight: bold;
}

Dive into the Codepen here to play around with the styles in this example.


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

Web DevelopmentFrontendCSS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.