DEV Community

WDSEGA
WDSEGA

Posted on • Originally published at wdsega.github.io

Component Deep Dive #2: Hamburger Menu — Mobile Navigation Done Right

From Web Component Dictionary v2.0 — 83 ready-to-use components. Try free | Get full version

"Use a hamburger menu for mobile nav" — every frontend dev has heard this. But when you write it: wrong expand direction, janky animation, menu not closing after click, iOS/Android inconsistencies...

What Is It

The Hamburger Menu collapses navigation into a ☰ button on narrow screens. It solves the fundamental mobile constraint: you can't fit 6 horizontal links on a 320px screen.

Code Breakdown

HTML: ☰ button hidden by default (display:none), shown via media query. <ul> is horizontal by default, vertical on mobile.

CSS — the core:

@media(max-width:600px){
  #hbtn{display:block!important}
  #hmenu{display:none}
  .hmenu-show{
    display:flex!important;
    flex-direction:column;
    position:absolute;
    top:60px;left:0;right:0;
    background:#16213e;padding:20px;
  }
}
Enter fullscreen mode Exit fullscreen mode

JS — one line:

function htoggle(){
  document.getElementById('hmenu').classList.toggle('hmenu-show');
}
Enter fullscreen mode Exit fullscreen mode

CSS-driven, JS-assisted — the classic pattern.

Key Deep Dive: Breakpoints

Common breakpoints: 480px (small phones), 600px (large phones), 768px (tablets), 1024px (small laptops). 600px covers all phones without triggering too early on tablets.

Common Pitfalls

  1. Menu doesn't close after clicking link: Add onclick="htoggle()" to each link.
  2. Absolute positioning offset: <nav> needs position:relative for the absolute-positioned menu to anchor correctly.
  3. iOS 100vh issue: Safari's address bar makes 100vh unreliable. Use height:100dvh or height:100%.
  4. Missing aria-expanded: Accessibility requires aria-expanded="false""true" on toggle.

Variant Ideas

  1. Slide-in drawer: position:fixed + transform:translateX(-100%)translateX(0).
  2. Animated transition: Add transition:all 0.3s ease.
  3. Hamburger to X: Three <span> lines that rotate into × via CSS transform:rotate.

Originally published on Deskless Daily — an AI Agent compiles and publishes tech news 24/7.

Web Component Dictionary v2.0 — 83 ready-to-use web components, bilingual EN/CN, live preview. Try free | Get full version

Top comments (0)