📝 CSS-Tricks 256: When to use @container queries

View this newsletter on the web.

[Robin]: Max Böck asks when should we use @container or @media queries?

While I think container queries will eventually replace most “low level” responsive logic, there are still a lot of good usecases for trusty media queries.

A combination of both techniques will probably be the best way forward. @media can handle the big picture stuff, user preferences and global styles; @container will take care of all the micro-adjustments in the components themselves.

Once @container queries get support in browsers and it becomes a part of our daily work, I can see how this question might be confusing for folks getting started in web development. Heck, I can see it being confusing for me! And yet, although Max makes a lot of great points in that piece, I think the quickest explanation between the two could be this:

@media queries are for page layout and @container queries are for components.

That’s a little simplistic but when it comes to component design (like a navigation or a button) you likely want that component to be aware of its environment and the width or height of its parent. Let’s say you want to throw that dropdown component into the sidebar, or grab that button group and put it into a bigger space than it was initially designed for. Those are the moments when @container queries will absolutely shine.

Layouts are a bit different because we don’t often want to nest layouts. If you have a 12-column grid, it’s unlikely you’ll want to nest that grid within another grid component—instead, you’d want the elements to inherit the grid. And that’s precisely what subgrid is for:

See how nested elements above (like the gray rectangle) is aligned to the grid gap of the outer container? That’s good ol’ subgrid and that means we can mostly avoid nesting grid elements within grid elements.

Anyway, I reckon in almost all instances when we’re designing a component we’ll want to use @container. But, saying that, I really hope @media queries aren’t treated later like the <table> element is today, where a ton of people are somehow under the impression that they are bad practice just because they were the best option to lay things out at the time.

Even though @container is on the horizon and it will be fancy new tool under our belt, @media still has its place and is still useful and relevant in layout and design.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s