DEV Community

loading...

CSS :focus-within pseudo-class

Felippe Regazio
web developer - js, [s]css, node, php, python - intp, lifelong learner, father, skateboarder. a strange carbon-based lifeform.
・1 min read

Imagine that you have a login card, and you want that login card to change its appearance when any of its children has been focused. You want the card to change when the user focus on any input (for example), or show some generic message, etc. That situation could happen with a myriad of everyday components that we are always writing and writing.

So, you dont need JS to achieve that behavior.
CSS can do that! You just need the :focus-within pseudo-class.

Here's an ugly demonstration ;P

And here`s the MDN definition:

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.)

font: https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

It has a regular support. But all the modern browsers still has fully implemented the :focus-within.

If you already knew it, thats cool! If not, thats cool anyway, because now you know. Thats all folks, just a quick and cool tip :)

Discussion (0)