Responsive Navigation Bar with Container Query

Build a navigation bar that switches between full menu, compact menu, and hamburger icon based on its container width using CSS container queries.

Integration Patterns

Detailed Explanation

Responsive Navigation with Container Queries

Container queries let you build a navigation component that adapts to its available space -- whether that is a full-width header, a sidebar, or a narrow panel.

The CSS

.nav-container {
  container: nav / inline-size;
}

/* Default: hamburger menu */
.nav-full { display: none; }
.nav-hamburger { display: flex; }

/* Medium: compact labels */
@container nav (min-width: 500px) {
  .nav-full {
    display: flex;
    gap: 0.5rem;
  }
  .nav-hamburger { display: none; }
  .nav-label { display: none; }
  .nav-icon { display: block; }
}

/* Wide: full labels */
@container nav (min-width: 800px) {
  .nav-label { display: inline; }
}

Three States

  1. Narrow (< 500px): Only a hamburger/menu button is visible. Suitable for narrow panels.
  2. Medium (500-799px): Icons are visible but text labels are hidden. Compact but functional.
  3. Wide (800px+): Full navigation with icons and labels.

Why Container Queries Are Better Here

A navigation component might appear:

  • In a full-width header (viewport = 1400px, nav = 1200px)
  • In a sidebar panel (viewport = 1400px, nav = 250px)
  • In a mobile layout (viewport = 375px, nav = 375px)

With media queries, you would need different breakpoints for each context. With container queries, the nav adapts to whatever space it receives.

Keyboard Accessibility

Remember to ensure keyboard navigation works in all states:

.nav-item:focus-visible {
  outline: 2px solid var(--primary);
  outline-offset: 2px;
}

Use Case

Use this pattern for navigation components that appear in headers, sidebars, or embedded panels. The component adapts its display density based on available space without any JavaScript resize observers.

Try It — CSS Container Query Builder

Open full tool