DEV Community

Discussion on: Let's build a responsive navbar and hamburger menu using HTML, CSS, and Javascript.

Collapse
 
nicozerpa profile image
Nico Zerpa (he/him)

Thank you for sharing!
There's a way to do it without using JavaScript, handling the menu visibility with CSS.

If you add a <div> containing only the hamburger button and the menu, you can use the :focus-within CSS pseudo-selector. :focus-within applies to an element if it has the focus, but also if one of its children is focused.

For example, if you write the HTML for the menu like this:

<div class="menu-container">
  <button type="button" class="hamburger">Menu</button>
  <nav class="navbar">...</nav>
</div>
Enter fullscreen mode Exit fullscreen mode

You can use the :focus-within selector like this:

.menu-container .navbar {
  display: none;
}
.menu-container:focus-within .navbar {
  display: block;
}
Enter fullscreen mode Exit fullscreen mode

Now, the <nav class="navbar"> will initially remain hidden, but it will appear when any child of <div class="menu-container"> is focused. For example, when you click on the hamburger button or some of the menu items.

Collapse
 
devggaurav profile image
Gaurav

Hey thank u so much for sharing this man! Will try this

Collapse
 
guin profile image
Angelika Jarosz

This is a cool solution i just tried out in my own code! Thanks for sharing! The only downside is once the menu is open, you have to click outside the hamburger to close it which from a user experience perspective could confuse a user for a second/ make them think your site has a bug. Unless you also have a work around to this that i am missing.