Beyond the Viewport
For over a decade, Responsive Web Design has relied on Media Queries. While media queries work well for adjusting layouts based on the screen size, they fall short in a component-driven world. If you place a sidebar widget into a wide main content area, it might look stretched; if you move that same widget to a narrow column, it breaks. CSS Container Queries solve this by allowing elements to respond to the size of their parent container rather than the browser window.
Defining a Container
To use container queries, you must first tell the browser which element should be watched. We do this using the container-type property. This establishes a containment context for the children of that element.
.card-wrapper {
container-type: inline-size;
container-name: sidebar-widget;
width: 100%;
}
In this example, inline-size tells the browser to track changes in the width of .card-wrapper. Setting a container-name is optional but helpful if you want to target specific containers in complex layouts.
Writing Container-Specific Styles
Once the parent is defined, you can use the @container rule to style child elements. This looks very similar to a standard media query but operates on the container's dimensions.
/* Default mobile-first styles */
.card {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* Adjust layout when the parent is wider than 400px */
@container (min-width: 400px) {
.card {
flex-direction: row;
align-items: center;
}
.card-image {
width: 150px;
aspect-ratio: 1 / 1;
}
}
Why This Matters for Modern UI
The primary advantage of container queries is true modularity. In the past, you might have written CSS classes like .card--large or .card--sidebar to manually adjust styles based on where a component lived. This required the developer to know the context ahead of time.
With container queries, the component is "self-aware." You can drop a .card into a header, a footer, or a main grid, and it will automatically choose the best layout for the space available. This reduces the amount of CSS you need to write and makes your components significantly more robust.
Container Query Units
Along with the @container rule, CSS introduced new relative units. These allow you to size elements based on the container dimensions rather than the viewport (vw/vh):
- cqw: 1% of a container's width.
- cqh: 1% of a container's height.
- cqmin: The smaller value of cqw or cqh.
- cqmax: The larger value of cqw or cqh.
.card-title {
font-size: clamp(1rem, 5cqw, 2rem);
}
Using 5cqw ensures the font scales fluidly as the container grows, providing a much more harmonious design than fixed pixel steps.
Current Browser Support
Container queries are now supported in all major evergreen browsers, including Chrome, Firefox, Safari, and Edge. If you are building modern web applications, it is time to shift your mental model from "page-based" design to "container-based" design. It is the missing piece of the responsive design puzzle.