For years, we’ve relied on media queries to make layouts responsive.
They work, but they come with a big limitation: they only consider the viewport size, not the size of the actual component.
Enter container queries, the game-changer for CSS layout design.
Why Should You Care?
Media queries assume every element adjusts based on the screen size.
That works—until you build reusable components that live in different contexts.
What if you want a card to shrink in a sidebar but expand in a main content area?
Media queries can’t help you. Container queries can.
How Container Queries Work
Instead of asking, “How big is the viewport?” container queries ask, “How big is my container?”
That means elements adjust their styles based on their parent container’s size instead of relying on global breakpoints.
The Syntax
First, define a container:
.card-container {
container-type: inline-size;
}
Then, write styles based on the container’s width:
@container (max-width: 400px) {
.card {
flex-direction: column;
}
}
Now, your card component adapts to its parent, not the entire screen.
Real-World Use Case
Let’s say you have a pricing card that appears in different layouts:
In the main content area, it’s wide.
In a sidebar, it’s narrow.
With container queries, you don’t need complex media query hacks. Just wrap it in a .pricing-container
and let the styles handle the rest.
Browser Support
Good news: All major browsers (except Safari on iOS 15 and earlier) support it.
Check Can I Use for details.
Final Thoughts
Container queries let us build truly responsive components—not just pages.
If you haven’t started using them yet, now’s the time. Your CSS will thank you.
What’s your take? Already using container queries, or still stuck in media query hell?
Thanks for reading! If you've enjoyed, feel free to like and follow me for more content!
I also share more content on Digital Minds, so be sure to check it out!
Top comments (0)