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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay