· By John Kavanagh

Building Responsive Navigation with CSS and JavaScript

A photograph of curved blue and white light streaks against black.
Image by Antoine Rault, licensed from Unsplash.

Responsive navigation is one of those front‑end jobs that looks simple until real content arrives.

The demo has five short links. The production site has two levels of navigation, long labels, account links, campaign links, and a content editor who quite reasonably wants to add another item later. The menu works at one breakpoint, then wraps awkwardly at another. JavaScript opens it nicely, until the script fails and the navigation disappears.

A good responsive navigation pattern starts by protecting the links.


The navigation should start as ordinary HTML.

That usually means a nav element, a list, and real anchors. Before adding collapse behaviour, check that the links are visible and usable in a simple layout.

The JavaScript layer can improve that experience:

  • open and close a compact menu
  • toggle sub‑navigation
  • update button text or state
  • trap accidental double opening
  • close the menu when the user follows a link

But JavaScript should not be the reason the links exist. If a menu is empty until a script builds it, the baseline is weaker than it needs to be.


Let CSS Handle Layout First

CSS should do as much of the responsive work as possible.

Media queries can switch between:

  • a horizontal list on wide screens
  • a wrapped list where space allows
  • a compact disclosure pattern on narrow screens
  • simpler spacing for cramped layouts

My article on media queries in CSS covers the mechanics. The important design decision is choosing breakpoints based on when the navigation actually stops fitting, not simply on device names.

"Tablet" and "mobile" are too vague. The menu cares about available width and content length.


Use a Button for Menu Toggles

If a control opens and closes the navigation, it is a button, not a link.

A link with href="#" and a click handler creates avoidable problems. It has no real destination, it can jump the page, and it says the wrong thing semantically.

Use a button with clear text. If the design uses an icon, keep a text label available for assistive technology. The button should also expose state, commonly with aria-expanded, and reference the menu it controls where possible.

This is not just an accessibility detail. It makes the behaviour easier to reason about and test.


Avoid Hiding the Menu Too Early

A common progressive enhancement mistake is hiding the compact menu in CSS before JavaScript has loaded.

If CSS hides the navigation by default and JavaScript is responsible for revealing it, a script error can remove the site's main links. A safer approach is:

  1. render the navigation visibly by default
  2. add an enhancement class when JavaScript runs
  3. use that class to enable the collapsed behaviour

My article on progressive enhancement with jQuery covers this pattern in more detail. It applies just as well to plain JavaScript.


Think About Overflow and Real Labels

Responsive navigation should be tested with real content, not placeholder labels.

Check:

  • long section names
  • many top‑level links
  • translated labels, if relevant
  • logged‑in and logged‑out states
  • active states
  • focus states
  • zoomed text

The menu should not rely on every label being one word. It should also not rely on the client never adding a sixth item.


Keep Sub‑Navigation Deliberate

Dropdowns and nested menus are where responsive navigation often becomes fragile.

If a top‑level item both opens a submenu and links to a section page, the interaction becomes ambiguous. Touch devices make that worse because hover is not reliable.

Prefer a clear pattern:

  • top‑level links navigate
  • adjacent buttons open submenus
  • submenu items are ordinary links
  • open state is visible and keyboard reachable

This may look slightly less minimal, but it is easier to use and maintain.

That accessibility point becomes more important when navigation patterns move into shared components. Accessibility in reusable front‑end components covers the same kind of state, naming, and keyboard behaviour at component level.


A Complete Nested‑Navigation Example

Here's a complete example of that pattern, checked in November 2026. Services is still a link, and the button beside it opens the submenu. On a narrow screen, Menu opens the whole list. These are ordinary navigation links, so there's no application‑menu role or focus trap, and neither menu needs hover. The WAI disclosure example with top‑level links explains that distinction well.

We start with every link visible and both buttons hidden, so you can still use the navigation if JavaScript never loads. This HTML belongs inside the page header. You can try its links in my complete example and tests.

<nav aria-label="Main" id="main-nav">
  <button type="button" id="menu-toggle" aria-controls="main-links"
    aria-expanded="true" hidden>Menu</button>
  <ul id="main-links">
    <li><a href="#home">Home</a></li>
    <li>
      <a href="#services">Services</a>
      <button type="button" aria-controls="service-links"
        aria-expanded="true" hidden>Service pages</button>
      <ul id="service-links">
        <li><a href="#accessibility">Accessibility reviews</a></li>
        <li><a href="#systems">Design systems and shared components</a></li>
      </ul>
    </li>
    <li><a href="#contact">Contact</a></li>
  </ul>
</nav>

The submenu stays in document flow, so opening it takes up a little more vertical space. That keeps this example from becoming an exercise in positioning overlays. Labels can wrap, there's room to tap the controls, and the wide layout can wrap whole groups. Use the same breakpoint in the CSS and JavaScript so they agree on when to switch layouts.

body { margin: 1rem; font: 1rem/1.5 system-ui; color: #182c3a; overflow-wrap: anywhere; }
nav { border-block: 1px solid #65717a; padding-block: 1rem; }
nav [hidden] { display: none !important; }
nav ul { list-style: none; padding: 0; margin: 0; }
nav li { min-width: 0; }
nav li ul { padding-inline-start: 1rem; }
nav a, nav button {
  display: inline-block; box-sizing: border-box;
  min-height: 44px; max-width: 100%; padding: .6rem;
  font: inherit; overflow-wrap: anywhere;
}
nav button { color: inherit; background: #e8eef2; border: 1px solid #65717a; }
a { color: #075985; }
:focus-visible { outline: 3px solid #9b4100; outline-offset: 3px; }
@media (min-width: 48rem) {
  #main-links { display: flex; flex-wrap: wrap; gap: 1rem; }
  #main-links > li { flex: 0 1 19rem; }
}

Load this script with defer, or as a module. It checks the controlled lists before hiding anything, then installs the handlers and enables the compact layout.

const nav = document.querySelector('#main-nav');
const menu = nav.querySelector('#menu-toggle');
const links = nav.querySelector('#main-links');
const wide = matchMedia('(min-width: 48rem)');
const pairs = [...nav.querySelectorAll('button[aria-controls]')].map(button => ({
  button,
  panel: document.getElementById(button.getAttribute('aria-controls')),
}));

// Validate the markup before hiding any links.
if (pairs.some(({ panel }) => !panel || !nav.contains(panel))) {
  throw new Error('A navigation disclosure has no matching list.');
}
const setOpen = ({ button, panel }, open) => {
  if (!open && panel.contains(document.activeElement)) button.focus();
  panel.hidden = !open;
  button.setAttribute('aria-expanded', String(open));
};
const main = pairs.find(({ button }) => button === menu);
const children = pairs.filter(pair => pair !== main);

for (const pair of pairs) {
  pair.button.addEventListener('click', () => {
    const open = pair.panel.hidden;
    setOpen(pair, open);
    if (pair === main && !open) children.forEach(child => setOpen(child, false));
  });
}
nav.addEventListener('keydown', event => {
  if (event.key !== 'Escape') return;
  const focused = document.activeElement;
  const child = children.find(({ button, panel }) =>
    !panel.hidden && (panel.contains(focused) || button === focused));
  if (child) {
    setOpen(child, false);
    child.button.focus();
  } else if (!wide.matches && !links.hidden) {
    setOpen(main, false);
    menu.focus();
    children.forEach(pair => setOpen(pair, false));
  } else {
    return;
  }
  event.preventDefault();
  event.stopPropagation();
});

const syncLayout = () => {
  if (wide.matches) {
    setOpen(main, true);
    if (document.activeElement === menu) links.querySelector('a').focus();
    menu.hidden = true;
  } else {
    menu.hidden = false;
    // A breakpoint change must not hide the link somebody is using.
    setOpen(main, links.contains(document.activeElement));
  }
};
wide.addEventListener('change', syncLayout);
children.forEach(pair => {
  pair.button.hidden = false;
  setOpen(pair, pair.panel.contains(document.activeElement));
});
syncLayout();

The important part is what happens before something disappears. Closing a list returns focus to its button if focus was inside. Widening the page moves focus from Menu to the first link before hiding Menu. Narrowing it keeps the main list open if somebody is already using one of its links. Resizing a window should not quietly put their place in the page out of reach.

Escape closes the active submenu first, then the compact navigation. Tab and Shift+Tab retain their ordinary browser behaviour. Moving outside the navigation leaves it open; this example has no overlay to dismiss and does not intercept outside clicks. There is no animation, so reduced‑motion mode needs no alternative transition.

CheckExpected behaviour
Enter or Space on a buttonToggle its list and aria-expanded together
Tab, Shift+Tab, and EscapeReach visible links; skip closed lists; return focus when closing
Touch a link or buttonNavigate or disclose respectively, without a first hover tap
Cross the breakpointKeep focus visible, including when Menu itself disappears
Long labels and enlarged textWrap without horizontal page overflow
Disable JavaScriptKeep all links available and hide the unused buttons

I've included a deliberately broken version in the tests too. Remove the focus transfer before hiding Menu, widen the page, and the first link no longer receives focus. The test catches that, then checks the working version. The Chrome checks also try a 320 CSS‑pixel viewport and text enlarged to 200%. You'll still need to try the browser's own zoom controls and listen to the navigation with the screen readers you support; checking button names and expanded states only tells us part of the story.


Wrapping Up

Responsive navigation is not just a breakpoint exercise. It is a resilience exercise.

Start with real links in usable HTML. Let CSS handle layout. Use JavaScript to enhance state and interaction, not to create the only path through the site. Then test the menu with real labels, real breakpoints, keyboard navigation, and JavaScript unavailable.

Key Takeaways

  • Navigation should begin as real links in usable HTML.
  • CSS should handle layout before JavaScript adds behaviour.
  • Menu toggles should be buttons with clear state.
  • Do not hide navigation by default and rely on JavaScript to reveal it.
  • Test with realistic labels, zoom, active states, and nested navigation.

Postscript

May 2026: This article is part of an archive restored from a previous version of my website on 27 May 2026. The original publication date is accurate. The article has since been restored and lightly edited for formatting, imagery, broken links, and current internal references.

November 2026: I've added a complete working example so that you can try the menu and submenu for yourself. It includes browser tests for keyboard navigation and changing screen sizes, particularly what happens to focus when a button or menu disappears.

Downloadable Resource

  • Responsive Navigation and Angular Form Examples

    Two worked examples: responsive navigation with nested disclosures and keyboard focus handling, and an Angular checkout form with asynchronous email validation. Includes source code, prebuilt examples, locked dependencies, and browser tests.

    First added

    Download ZIP

Have a complex web platform issue?

Tell me what is blocked, what has changed, and what needs to be true after the fix. I'll come back with a practical next step.