Today I'm going to share what I learned during this process by re-creating a simple Flexbox Navigation Menu that is also responsive. The end result is a mobile first menu that will show the logo and a hamburger toggle; desktop view shows all the navigation menu items minus the hamburger toggle.
To preview the end result, check out the final product over at my CodePen: Responsive Hamburger Menu.
First, let's set up the basic html for the menu.
A few notes about the html set up. The "Services" navigation menu item has a
tabindex="0" attached to the
<a> element. Do this because
<a> tags that don't contain an
href attribute are omitted from the default tab order. The toggle uses a Font Awesome Icon, so you'll want to make sure to add
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css"> to the
<head> section of your HTML document.
Let's style this thing! Here's a quick basic styling in CSS to get us going. Feel free to use whatever you'd like.
Since we are going for a mobile first menu, we are going to use Flexbox. With the menu closed, we want the logo and our menu toggle to sit next to each other at the top of the screen. One way we can do this is to ensure that the menu items span across the entire container. This way, Flexbox should display them stacked on each other. This will leave the logo and toggle at the top of the navigation menu side by side. Adding a bit more CSS to line thins up:
What did we do? We hid the
.item elements and aligned the flex items vertically and the horizontally by using
align-items. We are going to have the hidden items only show when the user toggles the hamburger via the
Since we only want the drop down menu to be seen when the toggle menu is used we hide it with
<script src="scripts.js"></script> to the bottom of your html just before the
querySelector(), we'll grab the menu and hamburger toggle and add a custom function which is called when the hamburger is clicked. Next up, we add the event listener to capture the click. Next let'ss get the drop down menu to work.
Grab all the menu items with
querySelectorAll(), then using a custom function we'll add and remove
.drop-down-menu-active to and from the clicked element. We finish it off with adding two event listeners for the drop down menu items. One for the click, and one for the keypress. Next we are going to make it easier for the user to exit the drop down menu when at the desktop view.
Now that we have that done, lets create the desktop menu.
When we are at desktop size, it hides the toggle and repositions the drop down menu.
And there you have it, you've now created a clean and simple responsive navigation menu for your website!