CSS Container Queries are a revolutionary feature that allows an element to style itself based on the size of its parent container, rather than the size of the entire browser viewport. This enables the creation of truly modular, reusable, and context-aware components.
The Old Problem: Viewport-Only Design 😫
For years, responsive design has relied on media queries. A media query checks the size of the entire browser window (the viewport) to apply styles. This works for overall page layout, but it fails for individual components.
Imagine you have a “card” component. On a blog post, it might be in a wide main content area. On the homepage, it might be in a narrow sidebar. With media queries, you’d have to write complex, location-specific styles. You couldn’t create a single, self-contained component that just “adapts” to the space it’s given.
Analogy: The Plant and the Pot 🌱
- Media Queries are like a plant that only cares if it’s sunny or cloudy outside (the viewport).
- Container Queries are like a plant that adapts its growth based on the size of the pot it’s actually in (the parent container). This is a much more intelligent way to grow.
How to Use Container Queries
Using them involves two simple steps:
1. Establish a Containment Context
First, you need to tell the browser which element will be the “container” that its children can respond to. You do this with the container-type
property.
CSS
.card-container {
container-type: inline-size;
}
This tells the browser that elements inside .card-container
can now query its width (inline-size
).
2. Write the Container Query
Next, you use the @container
at-rule, which works just like a media query, to apply styles to the elements inside the container when it reaches a certain size.
CSS
/* Default styles for the card */
.card {
display: grid;
grid-template-rows: 1fr auto;
}
/* When the container is 400px or wider, change the layout */
@container (min-width: 400px) {
.card {
grid-template-columns: 1fr 2fr;
grid-template-rows: auto;
}
}
Now, this card component is truly portable. It will automatically switch to a horizontal layout whenever you place it in any container that is wider than 400px, regardless of the overall page width.
The Benefits
- True Reusability: Create components that can be dropped anywhere in a layout and just work.
- Simpler Logic: Reduces the need for complex, location-based CSS classes or JavaScript to handle component styles.
- Component-Driven Design: It finally gives CSS the power to match the component-based architectures of modern JavaScript frameworks like React and Svelte.
Step 2: Offer Next Step
The article on CSS Container Queries is now complete. The next topic on our list is about WebAssembly (WASM). Shall I prepare that for you?