📝 CSS-Tricks 247: Container Queries and Career Laddering

View this newsletter on the web.

[Robin]: It’s been a long and winding road, but container queries are starting to arrive. They just landed in Chrome Canary. I first spotted this news on Andy Bell’s blog a few weeks ago when he made a great example and tutorial.

First up, we need to head to Chrome Canary and toggle on container queries in chrome://flags/. Once that’s done, we can write some quick HTML, like this:

<div class="parent"> <div class="child"> This is the child element </div> </div>

Now we can start to write CSS:

.parent { contain: layout inline-size; } .child { padding: 50px; background: blue; } @container (min-width: 700px) { .child { background: red; } }

That contain property there is performance-focused CSS to help the browser do more performant things with rendering and painting, and it has been part of the story of unlocking these container queries (usage is required here). The real fun part is @container (min-width: 700px) which is basically saying, When .parent is wider than 700px, change the background of .child to red.

Here’s a quick demo I made that you can check out in Chrome Canary:

Nothing too impressive, sure. But the remarkable thing here is that we finally have all these super powers to style a child element based on the width of its parent. Let’s say I wanted to change the text color or any components within .child if this parent element was in a sidebar. That’s now possible!

Ahmed Shadeed made a much more elaborate series of examples as to how we might use container queries in his “Say Hello to Container Queries” post:

A web page consists of different sections and components, and we make them responsive by using CSS media queries. There is nothing wrong with that, but it has limitations. For example, we can use a media query to show the minimal version of a component on mobile versus desktop.

Oftentimes, responsive web design is not about the viewport or the screen size. It’s about the container size.

He then made this fabulous diagram that illustrates the difference between media queries and container queries:

How useful are container queries going to be? Well, Scott Jehl said this half a decade ago.

I’m so thoroughly excited for container queries landing in more browsers in the near future because they allow us to make much more flexible and elegant components in our design system.

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 )

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