Sticky navbar with mobile drawer
A sticky top navigation that collapses into a slide-in drawer on small screens, with Escape to close and a backdrop.
Tailwind CSSNavigationnavbardrawerresponsivesticky
Live preview
Code
How it works
What it solves
A site header has to stay reachable while scrolling, show every link on wide screens, and turn into a usable menu on phones without a heavy framework. This pattern does all of that with one header, one drawer and about twenty lines of script.
How it works
The header uses sticky top-0 with a translucent background and backdrop-blur, so content slides underneath it. The desktop links live in a hidden md:flex list. On small screens a menu button toggles the drawer, which is a fixed panel moved with -translate-x-full and translate-x-0. The button keeps aria-expanded in sync and points to the drawer through aria-controls. A sibling backdrop closes the drawer on click, and a keydown listener closes it on Escape. While open, the page body gets overflow-hidden so the background does not scroll.
Adapting it
Swap the links in both lists (keep them in one JavaScript array if you generate markup). To open from the right, change the left anchor to right and flip the translate sign. Raise the breakpoint from md to lg for long menus.
Pitfalls
- A sticky header needs a parent without
overflow: hidden, or it silently stops sticking. - Return focus to the menu button after closing so keyboard users keep their place.
- Use
inertorhiddenon the closed drawer if it contains focusable links.
How to use it
- Paste
navbar.htmlas the first element inside<body>of a Tailwind 4 page. - Load
navbar.jswithdeferat the end of the page. - Replace the Acme logo text and the link list (desktop and drawer copies).
- Give the main content enough height to see the sticky behaviour.
Licence: DEV3 Snippet Licence. Free to use, change and ship in personal and commercial projects. Attribution is appreciated, not required. Please do not redistribute snippets as a collection.