:focus-within

Posted on June 11, 2018

css

It's been awhile since I've really spent time working in CSS, but I've recently had to build a template at work. It's taken a bit to get back in the swing of things, but I've learned a lot of cool new tricks. Well, at least new since the last time I did all this. The one I want to highlight in this blog post, however, is the CSS pseudo-class :focus-within.

:focus-within is similar to the pseudo-class :focus in that it applies certain styles to your site when an element has focus. The difference is that :focus only applies to a single element. When that single element has been focused, the styles are applied. With :focus-within, however, can be placed on a parent element and when any child element, or the parent element itself, is focused the styles will be applied.

This comes in really handy when you want to style a form when a child input is focused. Or, in my case, make a dropdown show up when a user enters an input field. In the case I was working on, I wanted a dropdown to show up that would contain suggestions as a person typed in an input. :focus-within makes that very simple. Here's the relevant part of the HTML for my search bar:

HTML demo code for the :focus-within dropdown

And here's the SCSS used to make everything work:

SCSS demo code for the :focus-within dropdown

As you can see, it really doesn't take that much HTML or CSS to get this done. The finished product is shown here:

A GIF showing the dropdown show and hide when focus is placed in the search box.

There are lots of ways to achieve this desired output, and there are lots of applications. But I was surprised at how easy this was and how quickly I was able to implement it. I definitely recommend it to anyone that is looking for similar functionality. It's only available in Chrome, Firefox, and Safari at this point, but if you can get away with that it's perfect.