Mobile 'Hamburger' Navigation

Mobile "Hamburger" Menus

Don't remove the "Menu" text from the menu. You can change the text to something else, but you want there to be words for screen readers to read.

HTML

<nav aria-label='Main Navigation' class='menu' >
  <button aria-expanded="false"><span aria-hidden="true">☰</span> Menu</button>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
    <li><a href="#">Works</a></li>
    <li><a href="#">FAQ</a></li>
  </ul>
</nav>

CSS

This CSS uses an overly specific CSS selectors because this page has multiple nav elements. You should simplify this CSS.

.menu button {
	display: none;
}

.menu button::after {
	content: "☰" ;

}

.menu button[aria-expanded="true"]:after {
	content: "✖" ;
}

.menu button:focus {
	outline: revert;
}

.menu button:hover {
	cursor: pointer ;
}

.mobile-nav ul {
	display: none;
}

.mobile-nav button {
	background-color: unset;
	border: none;
	display: block;
	font-size: 1.5em;
}

.mobile-nav button span {
	font-size: 1.5em;
}

ul.is-active {
	display: block;
}

@media (min-width: 45rem) {
	.mobile-nav ul {
	  display: flex;
	  justify-content: space-evenly;
	}
  
	.mobile-nav button {
	  display: none;
	}

}

JavaScript

(function(){
  const debug = false ;

  const nav = document.querySelector('nav.menu');
  const toggle = nav.querySelector('button');
  const navlist = nav.querySelector('ul');

  if ( nav && toggle && navlist ) {
    nav.classList.add('mobile-nav') ;

    toggle.addEventListener('click', function(){
      if ( debug ) { console.log('toggle was clicked') ; }
      if (navlist.classList.contains('is-active')) {
        this.setAttribute('aria-expanded', 'false');
        this.setAttribute('aria-label', 'Menu');
        navlist.classList.remove('is-active');
        if ( debug ) { console.log('remove is-active class') ; }

      } else {
        navlist.classList.add('is-active'); 
        this.setAttribute('aria-expanded', 'true');
        this.setAttribute('aria-label', 'Close Menu');
        if ( debug ) { console.log( 'add is-active class') ; }
      }
    });
  }
})();

Demo

Introduction

The following nav element will switch to a "hamburger" menu on small screens.

To test on a desktop, make the browser window very narrow. The navigation links will be hidden and then replaced with a button. Either click on the button, or tab to the button then press the "Enter" key to activate the menu.

Style the nav, button and links as desired — the browser's default styles for buttons is always ugly.