Sub topic 5
The hamburger menu
The hamburger menu hides the main navigation links behind a single button. Pressing the button shows or hides the list. This chapter builds one with semantic HTML, a small amount of JavaScript, and CSS that turns it into an ordinary horizontal menu on wide screens.
This chapter assumes you can write semantic HTML (header, nav, ul, button), lay out a row with flexbox, write a min-width media query, and select elements and attach event listeners in JavaScript. It also assumes you have read the earlier chapters on mobile constraints, the viewport tag, semantic navigation markup, and touch targets. The chapter after this one covers the accessibility of the toggle in more depth. Here you get a working, accessible baseline.
What the pattern does
A phone screen has little room. A row of five or six links with readable text and touch-sized spacing usually does not fit. The hamburger menu solves this by collapsing the links into one control, which frees the header for the logo and other content.
The pattern has three parts that must agree with each other:
- Markup: a button and a list of links, with the list hidden by default.
- Behavior: JavaScript that flips the visible state when the button is pressed.
- Presentation: CSS that shows the full list and hides the button when there is enough width.
At any moment the menu is in one of two states, and three events move it between them.
Step 1: The markup
Start with the viewport tag in the document head. Without it, mobile browsers lay the page out at a desktop width of about 980px and scale it down, so your media queries never see a narrow screen.
<meta name="viewport" content="width=device-width, initial-scale=1">
<header>
<a href="/">Site name</a>
<button id="menu-toggle" type="button" aria-expanded="false" aria-controls="site-menu">Menu</button>
<nav aria-label="Main">
<ul id="site-menu" hidden>
<li><a href="/products">Products</a></li>
<li><a href="/pricing">Pricing</a></li>
<li><a href="/docs">Docs</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>Each choice here has a reason.
- A
button, not adivor a link. Abuttonis focusable, responds to Enter and Space, and is announced as a button by screen readers. You get all of that without writing any code.type="button"stops it from submitting a form if the header is ever placed inside one. - A visible text label. "Menu" is clearer than an icon alone. Many people do not recognize the three-line icon. If you add an icon later, keep the text or give the button an accessible name some other way.
aria-expanded="false". This tells assistive technology whether the controlled content is currently shown. It starts asfalsebecause the list starts hidden.aria-controls="site-menu". This names the element the button operates. Support in screen readers is uneven, so treat it as a helpful hint and not as the thing that makes the menu work.- The
hiddenattribute on the list.hiddenremoves the element from rendering, from the accessibility tree, and from the keyboard tab order. A screen reader user cannot reach links in a closed menu, which matches what sighted users see. navwitharia-label="Main". Thenavlandmark lets assistive technology users jump straight to the navigation. The label separates it from any othernavon the page, such as a footer menu.
The button sits next to the nav, not inside it. That way the nav landmark contains only links. Placing it inside the nav is also acceptable, as long as you are consistent.
Step 2: The behavior
The script keeps two pieces of state in step: the button's aria-expanded attribute and the list's hidden property.
const toggle = document.getElementById('menu-toggle');
const menu = document.getElementById('site-menu');
toggle.addEventListener('click', () => {
const isOpen = toggle.getAttribute('aria-expanded') === 'true';
toggle.setAttribute('aria-expanded', String(!isOpen));
menu.hidden = isOpen;
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && !menu.hidden) {
toggle.setAttribute('aria-expanded', 'false');
menu.hidden = true;
toggle.focus();
}
});Read the click handler line by line:
- It reads the current state from the attribute.
getAttributereturns a string, so the comparison is against'true', not the booleantrue. - It writes the opposite value back.
String(!isOpen)turns the boolean into the string"true"or"false", which is what ARIA attributes require. - It sets
menu.hidden = isOpen. If the menu was open,isOpenistrue, so the menu becomes hidden. If it was closed,isOpenisfalse, so the menu is revealed.
The keydown handler lets a keyboard user close the menu with Escape. It then moves focus back to the toggle button. Without that step, focus would stay on a link that has just become hidden, and the keyboard user would lose their place on the page.
The attribute is the single source of truth in this code. Both the click handler and the Escape handler update the attribute and hidden in the same place in the same function body. If you later add a third way to close the menu, such as a click outside it, move the pair of lines into one setOpen(isOpen) function so they cannot drift apart.
Step 3: The CSS
The CSS is written mobile first. The base rules describe the narrow layout. One min-width media query then adjusts the wide layout.
#site-menu {
list-style: none;
margin: 0;
padding: 0;
}
#site-menu a {
display: block;
padding: 0.75rem 1rem;
}
@media (min-width: 48em) {
#menu-toggle {
display: none;
}
#site-menu,
#site-menu[hidden] {
display: flex;
gap: 1rem;
}
}Several details matter here.
- Link size. Each link is
display: blockwith0.75remof vertical padding on each side. With a normal line height of about 1.5rem, that gives roughly 48px of height. The whole row is tappable, not only the text. This follows the touch target guidance from the earlier chapter. - No
displayrule on the base list. Thehiddenattribute works because the browser's built-in stylesheet gives[hidden]adisplay: nonerule. Any author rule that setsdisplayon the same element, such asdisplay: flex, overrides it, and the element becomes visible even thoughhiddenis set. So the narrow layout deliberately sets nodisplayon#site-menu. - The
#site-menu[hidden]selector. On wide screens we want the list always visible, even when a script has lefthiddenset. The selector#site-menu[hidden]has higher specificity than the browser's rule and matches the same element, so the wide layout wins. It is deliberate and it is the reason the same markup serves both layouts. - The toggle disappears on wide screens. With
display: none, the button is removed from layout and from the tab order. Users on a wide screen never see a control that does nothing. 48emas the breakpoint. In media queries,emis relative to the browser's default font size, usually 16px, so48emis 768px. It also respects a user who has raised their default text size, which makes the menu switch to the collapsed layout sooner. Choose the breakpoint by where your links stop fitting, not by a device name.
The button itself needs a comfortable size as well. This rule is not part of the main example, but it is a sensible addition:
#menu-toggle {
min-height: 48px;
min-width: 48px;
padding: 0 1rem;
}How the three parts fit together
| Concern | Narrow screen | Wide screen |
|---|---|---|
| Toggle button | Visible, `aria-expanded` tracks state | `display: none` |
| Menu list | Controlled by the `hidden` attribute | Forced to `display: flex`, always shown |
| Who changes state | The click and Escape handlers | Nobody, the toggle cannot be reached |
The JavaScript does not need to know the screen width. It only toggles state. The CSS decides whether that state matters. This keeps the logic small and avoids resize listeners.
Common errors and edge cases
| Symptom | Cause | Fix |
|---|---|---|
| The menu never appears on a phone | The viewport meta tag is missing, so the page is laid out at about 980px and the narrow rules never apply | Add the viewport tag to the `head` |
| The menu is visible on load even though it has `hidden` | An author rule such as `display: flex` was added to `#site-menu` outside the media query | Set `display` only inside the wide media query, or write a rule for `[hidden]` that sets `display: none` |
| The first tap does nothing, the second works | The markup says `aria-expanded="true"` but the list is hidden, so the handler reads the wrong initial state | Keep the initial attribute and `hidden` in agreement |
| After pressing Escape, keyboard focus jumps to the top of the page | Focus was left on a link that became hidden | Call `toggle.focus()` after closing |
| A screen reader says "collapsed" while the menu is open | Only `hidden` was changed, not `aria-expanded` | Update both together |
| The links are unreachable if JavaScript fails | The list is hidden in the HTML and only a script can show it | See the callout below |
Two more edge cases are worth knowing:
- Resizing after opening. If a user opens the menu on a narrow window and then widens it, the toggle disappears and the CSS keeps the list visible. If they narrow it again, the menu is still open, which is consistent because the attribute and
hiddenwere never changed. Nothing breaks. You only need extra code if you want to reset the menu to closed at the breakpoint. - Escape on a wide screen. The handler can still run while
hiddenis false and the toggle isdisplay: none. Callingfocus()on an element that is not rendered has no effect, so this is harmless. The!menu.hiddencheck stops the handler from doing needless work when the menu is already closed.
Trade-offs of the hamburger menu
The pattern is simple to build and works for any number of links. Its main cost is discoverability. Links inside a closed menu are out of sight, and people tap hidden links less often than visible ones. Opening the menu is also an extra tap on every visit. Mobile designers often report lower use of hidden navigation than of visible navigation, so a hamburger menu suits sites with many sections or infrequently used links, but it is a weak home for the two or three actions people use constantly. Later chapters compare it with the tab bar and the priority menu and explain how to choose.
The placement of the toggle matters too. A button at the top of a tall phone screen is hard to reach with one thumb. That is another reason to consider the thumb-reach guidance from the earlier chapter when choosing this pattern.
Exercise
A developer adds #site-menu { display: flex; } to the base CSS, outside any media query. On a phone, the menu is now always visible and the toggle button no longer seems to do anything. Why does this happen, and how should the CSS be changed so the toggle works again while the list still shows on wide screens?
Show answer
The hidden attribute only hides the list through the browser's built-in [hidden] { display: none } rule. An author rule that sets display on the same element overrides it, so display: flex keeps the list visible even when hidden is set, and the script's changes to hidden have no visible effect. Remove display: flex from the base rule and set it only inside the @media (min-width: 48em) block. Use the selectors #site-menu, #site-menu[hidden] there, so the wide layout shows the list even when hidden is present.
Exercise
A keyboard user opens the menu, tabs to the "Docs" link, and presses Escape. List the three things the keydown handler does, and explain what goes wrong for that user if the last one is left out.
Show answer
The handler sets aria-expanded to "false" on the toggle, sets menu.hidden = true, and calls toggle.focus(). Without the focus() call, focus stays on the "Docs" link, which has just become hidden. The browser then has no visible focused element, and the user's position on the page is lost, often reset to the start of the document. Returning focus to the toggle puts them back on the control that opened the menu.