Focus vs Focus-Within

Laurie - Sep 3 '19 - - Dev Community

Today we're going to talk about a couple of different pseudo-classes. If you are unclear what a pseudo-class is I recommend starting with this post.

Focusable elements

We're going to discuss focus and focus-within, but before we do it's worth reviewing what focusable means in the context of CSS.

An element is focusable if you can tap it, click it or tab to select. Good examples of this are form inputs and links.

The focus and focus-within pseudo-classes are both triggered when a user focuses on an element, albeit in different ways.

focus

Let's review focus first. This pseudo-class is applied to an element. When that element is in focus the styling appears.

Take this example of a list of inputs. Each input has its own id with a corresponding focus style.

Depending on which input you select, it will have the associated background-color.

Pay attention to the fact that this pseudo-class responds to an elements state and applies styling to that same element. For our next example, that won't be the case.

How is focus-within different?

Focus-within is assigned to a parent element. The styling rules are applied when any child element receives focus. Selecting an input, clicking a link, etc.

As it turns out, our list example from before is a good one to use. If we assume each input is the child then that makes li the parent. So let's add focus-within to our li elements. As in our previous example, we're actually adding an id and associating that with each li element.

If we click on an input we see that the surrounding element receives color.

So what's actually happening? The li element is looking at the input inside of it. When that input receives focus the styles are applied. However, since the rule is on the li element, the style is applied to the li element, even though the state change occurs in the input.

Make sense?

The "grandparent" element

Let's look at another example. li elements have yet another parent, ul. What if we applied our focus-within pseudo-class to that element?

If we click on an input inside the ul the style is applied to the ul element.

Conclusion

These are really neat CSS features, and understanding the difference between them will help you apply styles more directly. Can't wait to see what you make!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .