Short answer first. A responsive hamburger menu is a normal list of links inside a nav element, plus a button with aria-expanded="false" that shows and hides that list on narrow screens. JavaScript only flips aria-expanded between true and false. CSS reads that value and shows or hides the list. Escape closes the menu and sends focus back to the button. No focus trap, no library.
If you're a beginner, read it from the top and click the live demo at every step, because a menu is something you have to feel with your fingers and your keyboard. If you already build menus every week, jump to the section about why the button isn't a checkbox and then to the part about JavaScript failing. Those two are where menus that look finished quietly break for real people.
This one picks up where the sticky header and hero article stopped. There, on a narrow phone, the links in the header wrapped onto a second line and I said the honest fix is to move them behind a menu button. This is that button. You don't need the sticky header to follow along; everything here works in a plain header too.
info
Tested with: jsdom (the browser simulation that runs in Node) on 2026-11-16, with the same page shell the live demo below uses. Every click, Escape press and focus move described in this article was run there, and all 88 CSS declarations were checked against the CSS grammar. Layout in a real browser was not measured for this article, so open the demo on your laptop and your phone and try it yourself.
Let's start with the problem itself, because it's not as obvious as it looks. A header on a laptop has around a thousand pixels of width. Your logo takes maybe two hundred, and five links fit next to it easily. A phone held upright gives you somewhere around 360 to 430 pixels. The same logo and the same five links simply don't fit on one line anymore.
So the browser does what it always does with content that doesn't fit: it wraps it. If your links sit in a flex row with flex-wrap, they drop to a second line, then a third. If they don't wrap, they push the page sideways and you get that horrible horizontal scroll on a phone. Neither of those is a bug in your code. It's just maths: more stuff than space.
You have three honest options. One, let the links wrap and design for it. With three short links that's often the best answer, and nobody needs a menu button. Two, make the row of links scroll sideways on its own, which some news sites do. Three, hide the links behind a button that shows them when someone asks. That third option is the hamburger menu, named after the three stacked lines on the button that look a bit like a burger if you squint.
Here's the thing most tutorials skip. Hiding your navigation is a cost, not a free trick. Links people can't see are links people use less, because they have to know the menu exists and tap it first. So reach for the button when you have too many links for the width, not because every website seems to have one. If your site has three links, try letting them wrap first.
tip
A quick test before you build any menu: open your page with the browser's device toolbar at 360 pixels wide and look at the header. If the links fit on one or two tidy lines, you might not need a menu at all. Fewer moving parts means fewer things to break.
Before we write code, let's name what we're building, because the name decides almost every line. What we're making is called a disclosure. That's a button that shows and hides a section of the page. Nothing more. An accordion of questions on a help page is a disclosure. A "Show more" button under a long review is a disclosure. Our menu is a disclosure whose hidden section happens to be a list of links.
Think of a coat closet with a door. The coats are always in the closet. Opening the door doesn't create the coats and closing it doesn't throw them away. It only decides whether you can see them right now. That's exactly our menu: the links are always in the HTML, and the button is the door.
The W3C keeps a reference for this called the ARIA Authoring Practices Guide, and it has a disclosure navigation example. It describes three things we'll copy. The button carries aria-expanded, which is false while the section is hidden and true while it's visible. The button carries aria-controls with the id of the section it shows and hides. And Escape closes an open section and puts focus back on the button that controls it.
What's aria-expanded, in plain words? It's an attribute that tells assistive technology, like a screen reader, whether the thing this button controls is open or closed. A sighted person sees the list appear. A blind person using a screen reader hears something like "Menu, button, collapsed" and then "expanded" after pressing it. Without that attribute they press a button and hear nothing change.
Why not role="menu"
You might find old tutorials that put role="menu" on the list and role="menuitem" on every link. It sounds right. It's a menu, after all. Don't do it.
In ARIA, the menu role means an application menu, like File, Edit and View in a desktop program. A screen reader that hears role="menu" expects arrow keys to move between items and a whole set of behaviour that a website's list of links doesn't have. The APG page says it plainly: its navigation is a menu only in the everyday sense, and it does not provide the complex functionality that assistive technologies expect from the menu role. A plain nav with a plain list of links is what people expect, and it's less code.
Why there's no focus trap
A focus trap is code that keeps the Tab key inside one area of the page, so focus can't wander behind a modal dialog. Some menu tutorials add one because the menu "looks like a popup". Our menu doesn't need it.
A modal dialog blocks the page behind it; you have to answer it before you do anything else. Our menu blocks nothing. It's part of the page, it sits right under the header, and when you Tab past the last link you simply carry on into the page. Trapping focus there would make it worse: WCAG, the accessibility standard most laws point to, has a rule called No Keyboard Trap (level A, the most basic level) that says if focus can move into a component with the keyboard, it must be able to move away from it with the keyboard too. A trap you wrote on purpose is still a trap.
Every piece of this starts with HTML, and we write it as if JavaScript doesn't exist. That's not paranoia. Scripts fail more often than you think: a slow phone connection that gives up halfway, a browser extension that blocks something, a typo in a different script on the same page that stops everything after it. If your links only exist when JavaScript works, those visitors get a header with a logo and nothing else.
<header class="site-header">
<a class="logo" href="/">Maple Street Books</a>
<nav class="site-nav" aria-label="Main">
<button class="nav-toggle" type="button" aria-expanded="false" aria-controls="nav-links">
<span class="nav-toggle-icon" aria-hidden="true"></span>
Menu
</button>
<ul class="nav-links" id="nav-links">
<li><a href="/books">Books</a></li>
<li><a href="/events">Events</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>Let's go through it from the top.
The header is the strip at the top of the page. Inside it, the logo is a normal link to the home page. Then comes nav, which tells the browser and screen readers "this is a block of navigation links". Screen reader users can jump straight to it. The aria-label="Main" gives it a name, which matters the moment you have a second nav, say in the footer, and people need to tell them apart.
Next, the button. It's a real button element, not a div with a click handler. A real button can be reached with Tab, pressed with Enter or Space, and is announced as a button, all for free. A div gives you none of that, and you'd have to rebuild each piece by hand and you'd probably forget one. type="button" says this button doesn't submit a form. Inside a form, a button without a type is a submit button, so I write the type every time out of habit.
aria-expanded="false" is the state we talked about: the list starts closed. aria-controls="nav-links" points to the id of the list this button opens. Inside the button, the empty span will become the three lines of the icon, and aria-hidden="true" tells screen readers to skip it, because three lines aren't something you can say out loud. The word "Menu" is real text. It's what a screen reader announces, and it also helps sighted people who don't know what three lines mean. Yes, they exist.
Finally, the list of links, a ul with one li per link, exactly like the card list in the render-lists article where every item had the same structure. The list has the id the button points to.
Notice what isn't here: no class like "hidden" on the list, and no hidden attribute on anything. In this HTML the links are visible. Whether they get hidden on a phone is a decision CSS and JavaScript make together later, and only when JavaScript has actually arrived.
warning
When I started, I built pages from my head until they looked good. No plan, and no thought for semantics or for people who don't use a mouse. A menu is where that habit shows fastest: a div with an onclick looks identical to a button, until someone tries to open it with a keyboard. Start from the right elements and half of the accessibility work is already done.
Now we style the version everybody gets: a header with the logo on the left and the links in a row on the right. This is also exactly what someone sees on a phone if JavaScript fails, so it has to look acceptable even when it wraps.
.site-header {
container: site-header / inline-size;
position: relative;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px 16px;
padding: 8px 16px;
background: #1f2a44;
color: #fff;
}
.nav-links {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 4px 16px;
}
.nav-links a { display: block; padding: 8px 4px; color: inherit; }
.nav-toggle { display: none; }Most of this is ordinary flexbox. display: flex puts the logo and the nav side by side. justify-content: space-between pushes the logo to the left and the nav to the right. flex-wrap: wrap lets the nav drop under the logo when there isn't room, instead of pushing the page sideways. gap sets the space between items: 8 pixels between rows and 16 between columns. If flexbox still feels like magic, the flexbox vs grid article walks through exactly this kind of row.
The list gets the same treatment. list-style: none removes the bullets, and the margin and padding resets remove the indentation browsers add to every list by default. Then flex and wrap again, so the links sit in a row and wrap politely if they must.
Each link gets display: block and some padding. Why? Because the padding makes the clickable area bigger than the text. A link that's only as tall as its letters is hard to hit with a thumb.
The two lines that will matter later are the first one and the last one.
container: site-header / inline-size turns the header into a container, which means elements inside it can ask "how wide is my header?" and change their style based on the answer. That's a container query. You probably know media queries, which ask "how wide is the screen?". On a real page, where the header is as wide as the screen, the two give the same answer. I use the container version here for one practical reason: the live demo further down sits inside this article, and with a container query you can switch the demo between phone and desktop width with a button, without resizing your browser. If you prefer media queries, @media (max-width: 40em) in the next step does the same job on a normal page.
.nav-toggle { display: none; } hides the menu button by default. Wide screens don't need it, and if JavaScript never runs, nobody needs it either, because a button that does nothing is worse than no button. We'll show it only on narrow headers and only when the script has loaded.
And position: relative on the header? That's for the open menu, which will hang just below the header. Keep it in mind for a minute.
Now the phone version. Two conditions have to be true before we hide anything: the header is narrow, and JavaScript is running. The first condition is the container query. For the second, the script will add a class called has-js to the nav when it starts. If the script never runs, the class never appears, and none of these rules apply.
@container site-header (max-width: 40em) {
.has-js .nav-toggle {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 44px;
padding: 0 12px;
font: inherit;
color: inherit;
background: transparent;
border: 1px solid currentColor;
border-radius: 6px;
cursor: pointer;
}
.has-js .nav-links { display: none; }
.has-js .nav-toggle[aria-expanded="true"] + .nav-links {
display: block;
position: absolute;
top: 100%;
left: 0;
right: 0;
padding: 8px 16px 16px;
background: #1f2a44;
}
.has-js .nav-links a { padding: 12px 4px; border-top: 1px solid #3b4a6b; }
}Read the first line as a sentence: "when the container called site-header is 40em wide or less, apply these rules". 40em is 640 pixels at the normal 16 pixel font size. There's nothing sacred about that number. The right breakpoint is the width where your links stop fitting, so find yours by narrowing the page and watching when the header starts to look crowded.
The first block shows the button. display: inline-flex lines up the icon and the word "Menu" side by side. min-height: 44px makes it comfortable to tap. Where does that number come from? WCAG 2.2 has a rule called Target Size (Minimum) at level AA, and it asks for at least 24 by 24 CSS pixels, with a few exceptions. 44 is comfortably above that floor. font: inherit and color: inherit matter more than they look: buttons don't inherit the font and colour of the page by default, so without these two lines your button shows up in a small system font that doesn't match anything around it.
The second block hides the list. Simple. And here's an important detail: display: none doesn't only make the links invisible. It also takes them out of the Tab order and away from screen readers. That's what we want. A keyboard user shouldn't have to Tab through four invisible links to get past a closed menu.
The third block is the heart of the whole article, so let's slow down. The selector reads: "a list with class nav-links that comes directly after a menu button whose aria-expanded is true". The plus sign means "the very next sibling". So the moment the button says it's expanded, the list right after it becomes visible. CSS doesn't keep its own idea of whether the menu is open. It reads the exact same attribute the screen reader reads.
Why does that matter so much? Because now there's only one place the truth lives. In a lot of menu code you'll see a script that adds an "open" class to the list and, separately, maybe, remembers to update aria-expanded. Two pieces of state, and sooner or later they disagree: the menu looks open while a screen reader says it's closed. When the visual state is driven by aria-expanded itself, they can't disagree. If the attribute is wrong, the menu looks wrong too, and you'll notice in five seconds instead of never.
The rest of that block positions the open list. position: absolute takes it out of the normal flow, top: 100% puts its top edge right at the bottom of the header, and left: 0 with right: 0 stretches it across the full width. Absolute to what? To the nearest ancestor that has a position set, which is the header with its position: relative from step 2. That's the reason that line was there. The background repeats the header colour so the panel looks like it grows out of the header.
The last rule gives the links in the open panel more padding and a thin line between them, because stacked links need clearer separation than links in a row.
info
Absolute positioning means the open menu covers the top of the page instead of pushing it down. That's the usual choice, and Escape, a click outside or a tap on a link closes it. If you'd rather push the content down, drop position, top, left and right, and give the nav a full-width row of its own. Both are fine. Pick one on purpose.
Here's the script that makes the button work. It's shorter than most people expect, because CSS already does the showing and hiding.
const nav = document.querySelector(".site-nav");
const button = nav.querySelector(".nav-toggle");
const links = nav.querySelector(".nav-links");
nav.classList.add("has-js");
function isOpen() {
return button.getAttribute("aria-expanded") === "true";
}
function setOpen(open) {
button.setAttribute("aria-expanded", String(open));
}
button.addEventListener("click", () => {
setOpen(!isOpen());
});The first three lines find the elements we need. querySelector takes a CSS selector and returns the first element that matches. I search for the button and the list inside nav, not in the whole document, so a second nav elsewhere on the page can never get picked up by mistake.
nav.classList.add("has-js") is the line that switches on the phone rules from step 3. Until this line runs, the page behaves as if there's no script: links visible, no button. Once it runs, the button appears on narrow headers and the links hide behind it. This is called progressive enhancement. The basic version works for everyone, and the better version is added on top only when the browser can handle it.
isOpen reads the current state straight from the attribute. Notice we compare with the string "true". Attributes are always strings, so getAttribute returns "true" or "false", never the boolean values. That trips people up: a check like if (button.getAttribute("aria-expanded")) is always true, because the string "false" isn't empty.
setOpen writes the new state. String(open) turns the boolean true into the string "true", for the same reason. This is the only place in the whole script that changes the state, so if something ever goes wrong, there's one function to look at.
The click handler flips it: if it's open, close it; if it's closed, open it. And that's all the button does. It doesn't touch the list, add classes or set styles. The CSS from step 3 sees the new attribute value and does the rest.
Why does Enter and Space work too, when we only listened for click? Because it's a real button. Browsers fire a click event on a button when you press Enter or Space on it. That's the free behaviour we got by not using a div.
A menu that only closes when you press the same button again is technically working and practically annoying. People expect three more ways out.
nav.addEventListener("keydown", (event) => {
if (event.key === "Escape" && isOpen()) {
setOpen(false);
button.focus();
}
});
links.addEventListener("click", (event) => {
if (event.target.closest("a")) setOpen(false);
});
document.addEventListener("click", (event) => {
if (isOpen() && !nav.contains(event.target)) setOpen(false);
});The first listener handles Escape. It sits on the nav, not on the button, because key events bubble up: whether focus is on the button or on the third link, the keydown event travels up through the nav and this listener hears it. If the key is Escape and the menu is open, we close it.
Then comes the line people forget: button.focus(). Think about where keyboard focus is when someone presses Escape. Often it's on one of the links inside the menu. We just hid those links with display: none. If we do nothing, focus was sitting on an element that's no longer on screen. The browser lets go of it, and where the next Tab press lands depends on the browser. The keyboard user is lost. Moving focus to the button puts them exactly where they opened the menu, and that's what the APG example describes too.
The second listener closes the menu when someone picks a link. On a normal site the click loads a new page and the menu closes by itself anyway. But if your links jump to sections on the same page, like #contact, the page doesn't reload, and without this line the menu would stay open on top of the section you just jumped to. event.target is the exact element that was clicked, and closest("a") walks up from it to find a link. If the click landed on a link, or on something inside a link, we close.
The third listener is the click outside. It sits on the whole document. If the menu is open and the click happened somewhere that isn't inside the nav, we close it. nav.contains(event.target) answers "is the clicked element inside the nav?". The button is inside the nav, which is why clicking it doesn't trigger this listener and fight with the toggle.
What about Tab? If someone tabs past the last link, focus moves on into the page and the menu stays open. I leave that alone on purpose. The panel only covers the top of the page, the next Escape or click closes it, and closing a menu just because focus moved is the kind of clever behaviour that surprises people more often than it helps them.
And what about turning a phone sideways, or resizing a laptop window, while the menu is open? On a wide header the button is hidden and the links are always visible, because the wide rules don't look at aria-expanded at all. The attribute might still say true on a button nobody can see, and that's harmless: display: none removes the button from the accessibility tree too. No resize listener needed.
Now the part everyone thinks of first: the icon. I left it for last on purpose, because it's decoration. The menu already works without it.
.nav-toggle-icon,
.nav-toggle-icon::before,
.nav-toggle-icon::after {
display: block;
width: 18px;
height: 2px;
background: currentColor;
transition: transform 0.2s ease;
}
.nav-toggle-icon { position: relative; }
.nav-toggle-icon::before,
.nav-toggle-icon::after {
content: "";
position: absolute;
left: 0;
}
.nav-toggle-icon::before { top: -6px; }
.nav-toggle-icon::after { top: 6px; }The three lines are one empty span plus two pseudo-elements. A pseudo-element is a piece of the page that CSS creates on its own: ::before and ::after are extra boxes attached to an element, which you style like any other element. So the span itself is the middle line, 18 pixels wide and 2 tall, and the two pseudo-elements are the top and bottom lines.
background: currentColor colours all three lines with the text colour of the button. Change the button's colour and the icon follows, which you'll be grateful for the day someone adds a dark theme. content: "" is required: a pseudo-element without content isn't drawn at all, even with a width and a background. Then position: absolute on the pseudo-elements, with the span as their positioned parent, lets us move them 6 pixels above and 6 pixels below the middle line.
Then the open state turns the three lines into an X:
.nav-toggle[aria-expanded="true"] .nav-toggle-icon { background: transparent; }
.nav-toggle[aria-expanded="true"] .nav-toggle-icon::before { transform: translateY(6px) rotate(45deg); }
.nav-toggle[aria-expanded="true"] .nav-toggle-icon::after { transform: translateY(-6px) rotate(-45deg); }
@media (prefers-reduced-motion: reduce) {
.nav-toggle-icon,
.nav-toggle-icon::before,
.nav-toggle-icon::after { transition: none; }
}Same idea as step 3: the state comes from aria-expanded, so the icon can never show an X while the menu is closed. When it's open, the middle line becomes transparent. The top line moves down 6 pixels to the middle and rotates 45 degrees. The bottom line moves up 6 pixels and rotates the other way. Two crossed lines: an X. The transition from the first block animates that change over 0.2 seconds.
The last rule is for people who told their operating system they want less motion. Some people get dizzy or sick from things moving on screen, and every major system has a setting for it. The media query prefers-reduced-motion lets your CSS read that setting. When it's on, we drop the transition and the icon simply switches from lines to an X. A tiny rotating icon is not the biggest motion problem on the web, but it costs three lines to respect the setting, so I always do it.
If you want something that isn't three lines, use an SVG inside the button with aria-hidden="true" on it. Keep the word "Menu" either way.
Here's the finished menu, with every piece from the steps above. It starts at phone width so you see the button. Open it, then try each way out: press the button again, press Escape, click somewhere in the page, or pick a link. Click inside the demo and use Tab, Enter and Escape without the mouse too. Then press "Full width" to see the desktop layout, and tick "Pretend JavaScript failed" to see what someone gets when the script never loads. The line under the demo shows the button's aria-expanded value as it changes.
<div class="demo-controls">
<button type="button" class="demo-width" data-width="360px" aria-pressed="true">Phone width</button>
<button type="button" class="demo-width" data-width="100%" aria-pressed="false">Full width</button>
<label><input type="checkbox" id="no-js"> Pretend JavaScript failed</label>
</div>
<div class="stage">
<header class="site-header">
<a class="logo" href="#top">Maple Street Books</a>
<nav class="site-nav" aria-label="Main">
<button class="nav-toggle" type="button" aria-expanded="false" aria-controls="nav-links">
<span class="nav-toggle-icon" aria-hidden="true"></span>
Menu
</button>
<ul class="nav-links" id="nav-links">
<li><a href="#books">Books</a></li>
<li><a href="#events">Events</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main class="page">
<h1 id="top">Welcome to Maple Street Books</h1>
<p>Open the menu, then press Escape, click outside it, or pick a link. <a href="#books">A link in the page</a> to Tab to.</p>
</main>
</div>
<p class="demo-state" aria-live="polite">Button: aria-expanded="false"</p>.demo-controls { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center; margin-bottom: 12px; font-size: 14px; }
.demo-width { font: inherit; padding: 6px 10px; border: 1px solid #1f2a44; border-radius: 6px; background: #fff; color: #1f2a44; cursor: pointer; }
.demo-width[aria-pressed="true"] { background: #1f2a44; color: #fff; }
.stage { width: 360px; max-width: 100%; border: 1px solid #ccd; border-radius: 8px; }
.page { padding: 16px; min-height: 260px; }
.page h1 { font-size: 1.25rem; margin: 0 0 8px; }
.demo-state { font: 13px/1.4 ui-monospace, monospace; color: #444; margin: 10px 0 0; }
.site-header {
container: site-header / inline-size;
position: relative;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px 16px;
padding: 8px 16px;
background: #1f2a44;
color: #fff;
}
.logo { color: inherit; font-weight: 700; text-decoration: none; padding: 8px 0; }
.nav-links {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 4px 16px;
}
.nav-links a { display: block; padding: 8px 4px; color: inherit; }
.nav-toggle { display: none; }
@container site-header (max-width: 40em) {
.has-js .nav-toggle {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 44px;
padding: 0 12px;
font: inherit;
color: inherit;
background: transparent;
border: 1px solid currentColor;
border-radius: 6px;
cursor: pointer;
}
.has-js .nav-links { display: none; }
.has-js .nav-toggle[aria-expanded="true"] + .nav-links {
display: block;
position: absolute;
top: 100%;
left: 0;
right: 0;
padding: 8px 16px 16px;
background: #1f2a44;
}
.has-js .nav-links a { padding: 12px 4px; border-top: 1px solid #3b4a6b; }
}
.nav-links a:focus-visible,
.nav-toggle:focus-visible,
.logo:focus-visible {
outline: 3px solid #ffd166;
outline-offset: 2px;
}
.nav-toggle-icon,
.nav-toggle-icon::before,
.nav-toggle-icon::after {
display: block;
width: 18px;
height: 2px;
background: currentColor;
transition: transform 0.2s ease;
}
.nav-toggle-icon { position: relative; }
.nav-toggle-icon::before,
.nav-toggle-icon::after {
content: "";
position: absolute;
left: 0;
}
.nav-toggle-icon::before { top: -6px; }
.nav-toggle-icon::after { top: 6px; }
.nav-toggle[aria-expanded="true"] .nav-toggle-icon { background: transparent; }
.nav-toggle[aria-expanded="true"] .nav-toggle-icon::before { transform: translateY(6px) rotate(45deg); }
.nav-toggle[aria-expanded="true"] .nav-toggle-icon::after { transform: translateY(-6px) rotate(-45deg); }
@media (prefers-reduced-motion: reduce) {
.nav-toggle-icon,
.nav-toggle-icon::before,
.nav-toggle-icon::after { transition: none; }
}const nav = document.querySelector(".site-nav");
const button = nav.querySelector(".nav-toggle");
const links = nav.querySelector(".nav-links");
nav.classList.add("has-js");
function isOpen() {
return button.getAttribute("aria-expanded") === "true";
}
function setOpen(open) {
button.setAttribute("aria-expanded", String(open));
showState();
}
button.addEventListener("click", () => {
setOpen(!isOpen());
});
nav.addEventListener("keydown", (event) => {
if (event.key === "Escape" && isOpen()) {
setOpen(false);
button.focus();
}
});
links.addEventListener("click", (event) => {
if (event.target.closest("a")) setOpen(false);
});
document.addEventListener("click", (event) => {
if (isOpen() && !nav.contains(event.target)) setOpen(false);
});
// Demo controls only: they are not part of the menu.
const stage = document.querySelector(".stage");
const state = document.querySelector(".demo-state");
function showState() {
state.textContent = 'Button: aria-expanded="' + button.getAttribute("aria-expanded") + '"';
}
document.querySelectorAll(".demo-width").forEach((control) => {
control.addEventListener("click", () => {
stage.style.width = control.dataset.width;
document.querySelectorAll(".demo-width").forEach((other) => {
other.setAttribute("aria-pressed", String(other === control));
});
});
});
document.querySelector("#no-js").addEventListener("change", (event) => {
setOpen(false);
nav.classList.toggle("has-js", !event.target.checked);
});
document.querySelectorAll('.page a, .nav-links a, .logo').forEach((link) => {
link.addEventListener("click", (event) => event.preventDefault());
});A note on the demo: the width buttons, the checkbox and the status line under it are only there so you can poke at the menu inside this article. They're not part of the menu. On your own site you'd use the HTML from step 1, the CSS from steps 2, 3 and 6, and the script from steps 4 and 5. If you're reading this on a phone, both width buttons look the same, because the whole demo is already narrow.
Look at what we actually built. A list of links that's always in the HTML. A button with one attribute that says open or closed. One line of CSS that shows the list when that attribute is true. A script whose whole job is to flip that attribute, plus Escape to close and send focus home.
That's the aha. The menu isn't a fancy component. It's a closet door. And because the CSS reads the same aria-expanded the screen reader reads, the menu you see and the menu a blind visitor hears are always the same menu.
Once you see it this way, the same pattern covers a lot more than navigation: the "Show filters" button in a shop, the answers on a help page, the "Read more" on a long review. Button, aria-expanded, aria-controls, a section that's always in the HTML. You'll build a dozen of them.
A good programmer thinks a few steps ahead. Here's where this menu goes wrong when it meets real sites, and what to do about it.
The hidden attribute that doesn't hide
A lot of people hide the button with the HTML hidden attribute and remove it with JavaScript. Reasonable idea, but watch this. The browser hides hidden elements with its own tiny CSS rule, [hidden] { display: none }. Your own CSS wins over the browser's. So the moment you write something like this:
.nav-toggle { display: inline-flex; }the button shows up even with the hidden attribute on it. In the test for this article, a button with hidden and that one rule had a computed display of inline-flex, and the same button without the rule had none. MDN's page on the attribute warns about exactly this: an element styled display: block is displayed despite the hidden attribute. That's why our version doesn't use hidden at all: the button is display: none in plain CSS and only appears under .has-js. If you do use hidden in your projects, add one rule to your base styles and the surprise is gone:
[hidden] { display: none !important; }The important flag here is one of the few places where it's the right tool: you're telling every other rule in the project that hidden really means hidden.
The checkbox trick
You'll find menus built with a hidden checkbox and a label styled as the hamburger, so CSS alone can open and close them with :checked. It's clever, and it works without JavaScript. I don't use it for site navigation. A screen reader announces it as a checkbox, "checked" or "not checked", which is a strange thing for a menu to be. It has no Escape. And the label isn't focusable on its own, so the checkbox has to stay focusable while it's visually hidden, which is easy to get wrong. The button plus a few lines of script is less clever and more honest.
The details element
Another way that needs no JavaScript is details and summary, the built-in disclosure element in HTML. On a phone it's genuinely close to what we want. The trouble is the wide screen: a closed details element hides its content no matter what your layout wants, so on desktop you'd need either the open attribute set by a script or newer CSS. You end up writing code anyway, just in a stranger place.
JavaScript failed, and the header got tall
Tick "Pretend JavaScript failed" in the demo at phone width. The links wrap under the logo and the header grows. It's not pretty, but every link is there and works. That's Plan B, and it's a good one. The bad version, which you'll see on real sites, hides the links in CSS from the start and relies on the script to show them. When the script fails, there's no navigation at all. If your header's CSS hides links without checking for has-js or something like it, that's the bug to fix today.
A long menu on a short screen
With four links the open panel is short. With twelve links, a phone turned sideways can be shorter than the panel. In a normal header that's fine, you scroll the page and reach the bottom links. In a sticky header it isn't: the panel stays pinned to the top with its header, and the links below the edge of the screen can't be reached by scrolling the page. The fix is two lines on the open list: a max-height in svh units, for example max-height: 70svh, and overflow-y: auto, so the panel scrolls on its own. Or question whether twelve links belong in the main navigation at all.
The focus outline you removed
Plenty of resets contain outline: none on buttons and links because someone found the focus ring ugly. Then keyboard users can't see where they are, and in a menu that opens and closes that's the end of it. The demo uses :focus-visible with a thick yellow outline. :focus-visible shows the ring when you use the keyboard and usually not when you click with a mouse, which is the compromise most designers are happy with.
Sticky header plus menu
If your header is sticky, like the one in the sticky header article, the open panel hangs below a header that stays at the top while the page scrolls under it. That works with the code above as is, because position: sticky also counts as a positioned ancestor for the panel's position: absolute. If you use the hide-on-scroll script from that article, also make sure the header never hides while the menu is open. A menu that slides off screen with its header is a fun bug to find, and not a fun one to ship.
warning
All of this is front-end behaviour. Hiding a link in a menu doesn't protect the page it points to. If a link should only be visible to logged-in users or admins, the server has to check who's asking when that page is requested, exactly like the server-side checks in the login form validation article.
HTML now has a popover attribute. You put popover on an element and popovertarget="its-id" on a button, and the browser opens and closes it without any script. MDN lists the Popover API as Baseline 2025, newly available, meaning it has worked in the latest versions of the major browsers since January 2025. An auto popover can be light dismissed: clicking outside it or pressing Escape closes it. That's two of our listeners for free.
So why didn't I use it here? Three reasons, and none of them is "it's bad". First, a popover lives in a special top layer above the whole page, and positioning it right under the header needs extra CSS that's still settling in browsers. Second, on wide screens we want the links visible all the time as a normal row, and that means overriding the browser's rule that hides closed popovers, which turns an elegant feature into a fight. Third, it's newly available, so visitors on older phones that don't update still exist. A browser that doesn't know the attribute ignores it, so the list just sits in the page and the button does nothing. You'd have to plan that case yourself.
It's worth watching. For something that really is a floating layer, like a small account menu or a tooltip-style panel, it's already a great fit. For the main navigation on a content site, the classic disclosure in this article is still what I'd ship, and it'll keep working when you switch.
One more thing for people who build with components. In React or any framework, the same rules apply: the button keeps aria-expanded in sync with your state variable, the CSS or the class names follow that one value, and the links are rendered on the server so they exist before any JavaScript arrives. Don't let a framework talk you into rendering the links only after hydration, because that throws away the Plan B we built in step 1.
If the CSS in steps 2 and 3 felt shaky, go back to HTML and CSS for beginners for the basics of elements and selectors, then flexbox vs grid for rows that wrap. If you want the header to stay at the top while you scroll, and to hide on the way down, the sticky header and hero article is the natural next piece, and this menu drops straight into it.
And if the idea of "the front end is only half the check" from the last warning made you curious, the login form validation article shows the same thinking with a form: what the browser can do for the user, and what only the server can be trusted with.
Then build one. Take a page you already have, add the button, and test it three ways: with a mouse, with only the keyboard, and with JavaScript switched off in your browser's developer tools. If all three work, you've built a better menu than a lot of sites you'll visit today.
You can do this and you have to. If you weren't capable I wouldn't spend my time on you. Just don't give up and you'll always have me on your side.
