Container Queries in Practice: Building Truly Modular Components
Container queries let components respond to their own context, not the viewport. Here is how I refactor components to use them. For years, responsive design meant media queries, and media queries meant one thing: the viewport. A card component looked one way on a phone and another on a desktop, regardless of where it actually sat on the page. I had a product card that needed to look different in a sidebar (narrow), a grid (medium), and a hero section (wide). all on the same page, all at the same viewport width. Media queries could not handle this. Container queries can. I want to go beyond the basics here. Most container query tutorials show a simple card that flips from stacked to horizontal. That is the hello world. In production, you need named containers, nested containers, container units, and a strategy for combining container queries with media queries. That is what I want to cover. Establishing a Container The first step is declaring a containment context on the parent element. container-type: inline-size establishes a container based on the inline (usually horizontal) dimension. This is the most common type because width is…