CSS Container Queries
In web development, we've long relied on media queries to adapt layouts for different screen sizes. But media queries only care about the viewport, not the element itself. Enter **CSS Container Querie
In web development, we've long relied on media queries to adapt layouts for different screen sizes. But media queries only care about the viewport, not the element itself. Enter CSS Container Queries — a game-changing feature that lets us style elements based on the size of their direct container rather than the viewport.
What Are Container Queries?
Container queries allow CSS to respond to changes in the size of a container element. With container-type: inline or block, you declare an element as a container. Then, using the new @container query rule, you can adjust styles based on that container's dimensions.
.my-container {
container-type: inline-size;
}
.my-card {
container-name: card;
@container card (min-width: 300px) {
display: grid;
grid-template-columns: 1fr 1fr;
}
@container card (max-width: 299px) {
display: block;
}
}
Why It Matters
Before container queries, responsive design meant nesting components for different breakpoints. Container queries let us build truly modular UI components that adapt to their environment, whether that's a sidebar, a drawer, a modal, or a card on a dashboard.
This is especially powerful for design systems. Components written for a specific viewport size can now adapt to their container, ensuring consistency across different layouts without rewriting media queries.
Practical Applications
- Component Libraries: Buttons, cards, and modals that behave differently depending on their container.
- Progressive Enhancement: Graceful fallbacks for older browsers by styling containers with defaults that degrade appropriately.
- Micro-Interactions: Dynamic layout shifts that feel more natural and less jarring.
Browser Support
As of late 2024, major browsers including Chrome, Firefox, Safari, and Edge have full support. This means you can start experimenting now.
Conclusion
CSS Container Queries represent a major shift in how we think about responsive design. Instead of fighting against the viewport, we empower our elements to think for themselves. This flexibility opens up new possibilities in building more adaptable, maintainable, and resilient web applications.