Keyboard Accessible Navigation Menus

When a site has a nav menu with a hierarchy of sub-menus, it is normal for these to be displayed as a series of dropdowns which are made visible when hovering of focusing on a menu item. If you want to access a tertiary sub-menu you can hover over the parent submenu item in the secondary sub-menu: the :hover applies to the entire element tree. However, if you are using the keyboard then :focus will not behave the same way. For this reason themes often use jQuery to toggle a focus class on each ancestor for whatever item is currently focused. This doesn’t work in AMP since custom JavaScript is not allowed. Nevertheless, there is now a way to achieve the same effect just with CSS via the new :focus-within pseudo selector. Beware that this is not yet recognized in IE/Edge (Can I Use?), so if you are on a paired AMP site and want to have a JS solution in addition to an AMP one, you’ll need to copy the ruleset specifically for using :focus-within. In the following example, the focus class continues to be used in non-AMP:

.main-navigation li:hover > ul,
.main-navigation li.focus > ul {
    left: auto;
    right: 0;
}

/* The :focus-within selector is not recognized by IE/Edge. */
.main-navigation li:focus-within > ul {
    left: auto;
    right: 0;
}

.main-navigation ul ul li:hover > ul,
.main-navigation ul ul li.focus > ul {
    left: auto;
    right: 100%;
}

/* The :focus-within selector is not recognized by IE/Edge. */
.main-navigation ul ul li:focus-within > ul {
    left: auto;
    right: 100%;
}Code language: CSS (css)