liveBook · Manning

Hamburger menu

As explained in CSS in Depth, Second Edition

A hamburger menu is a compact navigation pattern that represents a menu with an icon and reveals its items on activation.

A hamburger menu compresses navigation for small screens by hiding its links until a user activates a button. Keep the button and nav as sibling elements so they stack naturally in wider layouts; position the button to align it with the header. section 7.1.1

Build the pattern around these decisions:

  • Place the reveal button inside the nav so screen-reader users encounter it when navigating to that landmark. section 7.1.1
  • Hide the dropdown initially with display: none, then show it when the menu gains an is-open class. section 7.1.1
  • Use JavaScript to toggle is-open when the button is clicked or tapped. section 7.1.1
  • Remember the trade-off: hiding main navigation saves space but can reduce interaction with those links. section 7.1.1
Listing 7.3 Mobile menu styles
.menu {
  position: relative;     #1
}

.menu-toggle {
  position: absolute;
  top: -1.2em;            #2
  right: 0.1em;

  border: 0;        #3
  background-color: transparent;

  font-size: 3em;
  width: 1em;
  height: 1em;
  line-height: 0.4;
  text-indent: 5em;         #4
  white-space: nowrap;
  overflow: hidden;
}
.menu-toggle::after {
  position: absolute;
  top: 0.2em;
  left: 0.2em;
  display: block;
  content: "\2261";     #5
  text-indent: 0;
}

.menu-dropdown {
  display: none;
  position: absolute;
  right: 0;
  left: 0;
  margin: 0;
}

.menu.is-open .menu-dropdown {
  display: block;           #6
}

Inspect the CSS pattern for positioning the button, hiding the dropdown, and revealing it through the open state. section 7.1.1

How CSS in Depth, Second Edition covers it

How deep it goes
Explains markup structure, CSS visibility, positioning, JavaScript state, accessibility placement, and interaction trade-offs.
Examples
Demonstrates a mobile navigation with a hamburger button, hidden dropdown, open-state class, and styled link list.
What you can do after
Builds and evaluates a responsive hamburger menu with CSS and JavaScript while considering accessibility and interaction costs.
How it connects
Connects responsive design, navigation landmarks, dropdown menus, CSS positioning, and JavaScript class toggling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of CSS in Depth, Second Edition. The section links point to the parts of the book it draws on.