Sub topic 2
The Hamburger Menu
Assume you know semantic HTML, CSS flexbox and media queries, and basic JavaScript event handling. Mobile navigation must fit a narrow viewport and remain usable with a thumb. A hamburger menu hides secondary links behind a button while keeping the page header compact.
The hamburger menu
Start with a real button and a semantic nav. The hidden attribute keeps the closed menu out of the keyboard navigation order.
<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>
</ul>
</nav>
</header>Making the menu toggle accessible
The button must report its state. aria-expanded says whether the menu is open, and aria-controls identifies the controlled list. Keep both the ARIA state and hidden property synchronized.
const toggle = document.querySelector("#menu-toggle");
const menu = document.querySelector("#site-menu");
toggle.addEventListener("click", () => {
const open = toggle.getAttribute("aria-expanded") === "true";
toggle.setAttribute("aria-expanded", String(!open));
menu.hidden = open;
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && !menu.hidden) {
toggle.setAttribute("aria-expanded", "false");
menu.hidden = true;
toggle.focus();
}
});On wider screens, show the links permanently and hide the toggle.
#site-menu {
list-style: none;
margin: 0;
padding: 0;
}
@media (min-width: 48em) {
#menu-toggle {
display: none;
}
#site-menu,
#site-menu[hidden] {
display: flex;
gap: 1rem;
}
}The bottom tab bar
A bottom tab bar suits a small set of high-frequency destinations, such as Home, Search, Orders, and Account. Give each link a large touch target and mark the current page with aria-current.
<nav class="tab-bar" aria-label="Primary">
<a href="/home" aria-current="page">Home</a>
<a href="/search">Search</a>
<a href="/orders">Orders</a>
<a href="/account">Account</a>
</nav>
<style>
.tab-bar {
position: fixed;
inset: auto 0 0;
display: flex;
background: white;
border-top: 1px solid #ccc;
padding-bottom: env(safe-area-inset-bottom);
}
.tab-bar a {
flex: 1;
min-height: 48px;
display: grid;
place-items: center;
}
</style>Add viewport-fit=cover to the viewport meta tag when using the safe-area inset. Also add bottom padding to page content so the fixed bar does not cover the last content.
Exercise
Which attribute identifies the navigation list controlled by the hamburger button?
Show answer
aria-controls identifies the controlled element, while aria-expanded reports whether it is open.