For years, we've been asking for container queries. Media queries let us respond to the viewport size, but what we really wanted was to style components based on their container size. Finally, that day has arrived.

The Problem with Media Queries

Consider a card component. In a wide sidebar, it should be compact. In the main content area, it can stretch out. With media queries, we'd need to know exactly where the card will be used and write specific breakpoints for each context.

This creates tight coupling between components and their containers. Not ideal for reusable design systems.

Enter Container Queries

Container queries flip the script. Instead of asking "how wide is the viewport?", we ask "how wide is my container?". This makes components truly self-contained.

Container Query Units

Along with @container, we get new container query units that are relative to the container dimensions:

  • cqw - 1% of container width
  • cqh - 1% of container height
  • cqi - 1% of container inline size
  • cqb - 1% of container block size
  • cqmin - smaller of cqi or cqb
  • cqmax - larger of cqi or cqb

Real-World Example

The blog post cards on this site use container queries. Resize your browser and watch how they adapt—not to the viewport, but to the space available in the grid.

Browser Support

Container queries are supported in all modern browsers as of 2023. For this blog, I'm targeting cutting-edge browsers only, so no fallbacks needed. In production, you might want to provide a reasonable default layout for older browsers.

The era of truly portable, context-aware components is here. No more viewport-based hacks. No more "this component only works in the sidebar". Just clean, containerized CSS.

Further Reading