23 March 2026

Container Queries for Responsive Nav

Swapped media queries for CSS container queries on my site's navigation. The header is the container — the nav responds to its actual width, not the viewport. Same result today, but far more composable if the layout ever changes.

I recently refactored my site's responsive navigation from media queries to CSS container queries. Instead of asking "how wide is the viewport?", the nav now asks "how wide is my header?"

The change is simple. The header becomes a named container:

.main-header {
  container-name: header;
  container-type: inline-size;
}

Then nav breakpoints use @container instead of @media:

/* before */
@media (min-width: 900px) {
  .nav-toggle { display: none; }
}

/* after */
@container header (min-width: 900px) {
  .nav-toggle { display: none; }
}

Since the header is fixed and spans the full viewport, the behavior is identical right now. But the mental model is better — the nav is responding to its own context, not a global viewport size. If I ever nest this nav inside a sidebar or a narrower layout, it just works.

Container size queries have ~96% global browser support (Chrome 105+, Firefox 110+, Safari 16+). No polyfill needed.