Say Hello to CSS Container Queries

Avatar of Robin Rendle
Robin Rendle on (Updated on )

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

Container queries are finally here! Now available behind a flag in the latest version of Chrome Canary, you can go ahead and experiment to your heart’s content. Oh, and if you’re not familiar with container queries then check out this post by Ethan Marcotte about why they’re so dang important.

Ahmad Shadeed described his excitement and showcased a ton of great use cases for problems that container queries solves:

I haven’t been more excited for a CSS feature like I’m now in the past six years I spent as a front-end developer. The prototype of container queries is now available behind a flag in Chrome Canary. Thanks to efforts from smart people like Miriam Suzanne and other folks.

I remember seeing a lot of jokes about the support for CSS container queries, but they are finally there.

Once you’ve activated the feature in chrome://flags you can then begin to write code like this:

.parent {
  container: layout inline-size;
}

@container (min-width: 400px) {
  .child {
    display: flex;
    flex-wrap: wrap;
  }
}

First off, you need to tell the parent component that a child needs to change size (that’s the container: layout inline-size part). Next, you can use a new kind of query called @container which will detect when the parent of an element changes width.

Andy Bell also made a bunch of great examples when he argued that we often need elements to change based on the size of the parent element more so than the width of the browser window, especially when it comes to typography:

Most importantly with container queries, we can set typography contextually! This for me is the most needed feature in design system implementations and why I constantly wish we had container queries. We can respond with media queries and set font sizes etc that way, but when you have no idea where an element will end up, this isn’t an ideal approach. Now we have container queries, we can make type adjustments that actually make sense a lot easier than before.

This post reminds me that Miriam Suzanne made an excellent proposal where you can read more about how container queries were designed and all the various snaffus and problems that came up along the way. It’s so neat to see a document like this that shows CSS being improved in public.

Personally, I believe this is the biggest improvement to CSS since Grid. It opens up all sorts of elegant solutions to problems we work around on a daily basis. I hit a snag just the other day when I wanted to set the type of an element in a sidebar depending on the width of the element wrapping it. And gah — it just wasn’t possible without introducing a bunch of weird hacks!

Container queries aren’t just some far-flung pipe dream now. They’re here to stay.

Direct Link →