DEV Community

Cover image for CSS: Best Practices for Multi-Level Navigation
Taufik Nurrohman
Taufik Nurrohman

Posted on

CSS: Best Practices for Multi-Level Navigation

Just get to the point, the key is to use the CSS adjacent sibling selector (the + selector), child selector (the > selector) and the new :focus-within pseudo-class selector:

/*
 * Hide sub-menu(s) by default.
 */
nav li ul {
  display: none;
}

/*
 * Image 1: Adjacent sibling selector to show the
 * closest sub-menu when a user focuses on a menu
 * item link that has a sub-menu next to it.
 */
nav li a:focus + ul {
  display: block;
}

/*
 * Image 2: Child selector to show the closest sub-menu
 * when a user hovers on a menu item with a sub-menu.
 */
nav li:hover > ul {
  display: block;
}

/*
 * Image 3: Focus-within selector to keep the sub-menu
 * visibility when a user moves the focus to the sub-menu
 * item link(s).
 */
nav li:focus-within > ul {
  display: block;
}
Enter fullscreen mode Exit fullscreen mode
/*
 * Image 2: Child selector to keep the menu item link hover
 * effect when a user moves the pointer to the sub-menu.
 */
nav a:hover,
nav li:hover > a {
  background: blue;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)