In this lesson, we are going to use the :focus-within pseudo class as a CSS only way improve the accessibility of a navigation menu.
If I were to use :focus on the
<li>, it wouldn't work because the list items have a tabindex of -1.
:focus-within represents an element that has received focus or contains an element that has received focus. So when it's child, the anchor, receives focus, we can use the same thing that we do on the hover effect. Be wary of browser support though!
If you have to support IE and Edge check out my other lessons: Expand a Menu on a Focus Event to Improve Accessibility and Collapse a Submenu on the Blur Event to Improve accessibility
Instructor: [0:00] Here, we have a navigation. When you hover over this navigation item, you'll see that the submenu appears. However, when you tab to them, so tab, tab, it doesn't open.
[0:14] Let's quickly go over the html. We have a <nav> with a <ul> with the class of "menu," and then a bunch of list items. When there's a submenu, we have a <ul> submenu that's nested underneath that menu item.
[0:32] Here, we're going to do something called :focus-within. We're going to take this styling right here that transforms scale y1, and we're going to apply that same styling to it.
[0:46] We're going to add the pseudo-class focus within .submenu, and save that. When we refresh, we should be able to focus and open it up. It goes away when we tab away from it.