Menu

Tutorials

Building Accessible Keyboard-Navigable Modals and Menus with Semantic HTML

Table of contents (7 sections)

Building a modal dialog or dropdown navigation menu from scratch with nested <div> elements looks deceptively simple until you test it with a keyboard or screen reader. Suddenly, pressing Tab escapes behind the backdrop, pressing Escape does nothing, screen readers keep reading background links, and closing the modal drops keyboard focus back to the top of the page.

Modern browsers solve almost all of those problems natively. By combining semantic HTML landmarks, the native <dialog> element, and the global inert attribute, you ship smaller JavaScript bundles with rock-solid accessibility. If you are brushing up on foundational HTML and CSS patterns, pair this guide with Best Udemy free courses HTML / CSS.

Why Native Semantic HTML Beats Custom Div-Soup Overlays

Custom <div role="dialog"> implementations force your team to re-implement browser top-layer stacking, z-index battles against sticky headers, backdrop rendering, keyboard dismissal, and background focus isolation in JavaScript. Every line of custom overlay plumbing adds bundle weight and edge-case bugs.

Worse, heavy third-party modal scripts and layout-thrashing overlays can hurt interaction responsiveness and visual stability, metrics tracked closely in our Core Web Vitals in 2026: How to Improve Website Performance guide. Native elements offload stacking and accessibility semantics straight to the browser engine.

RequirementCustom Div OverlayNative <dialog> + inert
Top-layer stacking above sticky headersManual z-index escalationAutomatic browser top layer via showModal()
Backdrop stylingExtra wrapper element in DOMBuilt-in ::backdrop CSS pseudo-element
Escape key dismissalCustom keydown listenerBuilt-in cancel event on modal dialogs
Background page isolationManual aria-hidden + tabindex sweepingAutomatic for showModal(); inert for custom drawers

Implementing Modal Dialogs with <dialog>, showModal(), and closedby

As documented on MDN’s <dialog> reference, the HTML <dialog> element has been Baseline Widely available since March 2022. Calling dialog.showModal() promotes the dialog into the browser’s top layer, renders a ::backdrop pseudo-element, and prevents interaction with the rest of the page automatically.

Two important rules from MDN keep <dialog> behavior compliant: always open modal dialogs with showModal() (never just toggling the open attribute, which creates a non-modal box without top-layer isolation), and never put tabindex on the <dialog> element itself. Instead, place autofocus on the primary close button or first safe interactive control inside the dialog, and check browser support for newer attributes like closedby="any" when light-dismiss backdrop clicks are desired.

html<button type="button" id="open-settings">Open notification settings</button>
 
<dialog id="settings-dialog" aria-labelledby="settings-title" closedby="any">
  <div class="dialog-header">
    <h2 id="settings-title">Notification settings</h2>
    <button type="button" id="close-settings" aria-label="Close dialog" autofocus>Close</button>
  </div>
  <form method="dialog">
    <label>
      <input type="checkbox" name="release_alerts" checked />
      Email me security release notes
    </label>
    <div class="dialog-actions">
      <button type="submit" value="cancel">Cancel</button>
      <button type="submit" value="save">Save preferences</button>
    </div>
  </form>
</dialog>

Notice <form method="dialog">: submitting any button inside a dialog form closes the dialog natively without a page reload and sets dialog.returnValue to the clicked button’s value.

Using the inert Attribute to Isolate Background Page Content

While dialog.showModal() makes the rest of the document inert automatically, non-dialog patterns such as slide-out mobile navigation drawers that sit inside your main layout tree need explicit background isolation. That is what the HTML inert global attribute solves.

Setting inert on a container (such as <main> and <footer> while a full-screen mobile menu drawer is open) instructs the browser to ignore pointer clicks, text selection, keyboard focus, and assistive technology discovery for that entire subtree in a single boolean property, eliminating fragile loops that manually toggle tabindex="-1" on dozens of links.

Mechanical keyboard close-up illustrating keyboard-first web accessibility
Keyboard-first navigation requires predictable Tab order, visible focus outlines, and clean Escape handling. Image: Anas Alshanti (CC0), via Wikimedia Commons.
javascriptconst openBtn = document.getElementById("open-settings");
const closeBtn = document.getElementById("close-settings");
const dialog = document.getElementById("settings-dialog");
 
let lastFocusedElement = null;
 
openBtn.addEventListener("click", () => {
  lastFocusedElement = document.activeElement;
  dialog.showModal();
});
 
closeBtn.addEventListener("click", () => {
  dialog.close("dismiss");
});
 
dialog.addEventListener("close", () => {
  if (lastFocusedElement instanceof HTMLElement) {
    lastFocusedElement.focus();
  }
});
 
// Accessible mobile navigation drawer using inert
const menuToggle = document.getElementById("menu-toggle");
const navDrawer = document.getElementById("mobile-nav");
const mainRegion = document.querySelector("main");
 
function setDrawerOpen(isOpen) {
  menuToggle.setAttribute("aria-expanded", String(isOpen));
  navDrawer.hidden = !isOpen;
  mainRegion.inert = isOpen;
  if (isOpen) {
    navDrawer.querySelector("a, button")?.focus();
  } else {
    menuToggle.focus();
  }
}

Keyboard Navigation, Focus Trapping, and Focus Restoration Rules

Whether you use native <dialog> or a custom navigation disclosure, your keyboard contract must match the WAI-ARIA Authoring Practices Guide (APG) Modal Dialog Pattern. That specification defines four non-negotiable rules:

  • Background isolation: Content underneath an open modal must be inert so neither keyboard focus nor screen reader virtual cursors wander outside the dialog.
  • Contained Tab cycling: Pressing Tab on the last focusable control wraps back to the first control inside the modal, and Shift+Tab wraps in reverse.
  • Escape dismissal: Pressing Escape closes the modal dialog or open navigation menu cleanly.
  • Focus restoration: Closing the overlay returns keyboard focus to the exact button that opened it (or a logical container if the trigger was removed from the DOM).

Keep Navigation Menus Simple Before Adding ARIA Menu Roles

A common accessibility mistake is applying role="menu" and role="menuitem" to website top-bar navigation. WAI-ARIA menu roles imply desktop application behavior where arrow keys move between items and Tab exits the entire menu bar. For standard website navigation links, stick to a semantic <nav> containing an unordered list of real <a href> links and a <button aria-expanded="false"> toggle for mobile drawers. Adding a global Escape listener when the drawer is open lets keyboard users dismiss the menu quickly and snap focus back to the toggle button.

Styling ::backdrop, Visible Focus Rings, and Reduced Motion

Native dialogs also deserve intentional CSS so keyboard focus remains unmistakable and motion preferences are respected. Use dialog::backdrop to dim the page cleanly, style interactive controls with :focus-visible so keyboard focus rings stay high-contrast without flashing on mouse clicks, and guard entrance animations inside a reduced-motion media query.

cssdialog#settings-dialog {
  border: 1px solid #d0d7de;
  border-radius: 12px;
  max-width: 32rem;
  padding: 1.5rem;
}
 
dialog#settings-dialog::backdrop {
  background: rgba(15, 23, 42, 0.55);
  backdrop-filter: blur(2px);
}
 
#settings-dialog :is(a, button, input):focus-visible,
#mobile-nav :is(a, button):focus-visible {
  outline: 3px solid #0369a1;
  outline-offset: 2px;
}
 
@media (prefers-reduced-motion: no-preference) {
  dialog#settings-dialog[open] {
    animation: dialog-pop 140ms ease-out;
  }
}

Testing Accessibility with Keyboard-Only Navigation and Screen Readers

Never mark a modal or menu complete based solely on automated linter scores. Automated tools catch missing aria-labelledby attributes or contrast failures, but they cannot tell you whether focus feels lost when closing a dialog.

  • Unplug your mouse for two minutes: Open the page, press Tab and Shift+Tab to reach the trigger, press Enter or Space, cycle through every control inside the modal, press Escape, and verify the visible focus ring returns to the trigger button.
  • Verify visible focus indicators: Never write outline: none without a high-contrast :focus-visible replacement ring.
  • Test with prefers-reduced-motion: Wrap dialog entrance transitions in @media (prefers-reduced-motion: no-preference) so motion-sensitive users do not experience jarring zooms.
  • Smoke-test in a screen reader: Verify VoiceOver (macOS), NVDA (Windows), or Orca (Linux) announces the dialog title via aria-labelledby when opened and cannot browse background links while the modal is active.

Good accessibility is mostly subtraction: use native dialog and nav semantics first, toggle inert for background isolation, and restore focus to the trigger when closing.

By leaning on native <dialog>, showModal(), inert, and clean <nav> markup, you eliminate fragile focus-trapping libraries while giving keyboard and screen reader users a fast, predictable interface.

Featured image credit: Moiz Syed (CC BY-SA 4.0), via Wikimedia Commons.