I saw this tweet by Una where she announced that CSS container queries are now available under a flag in Chrome Canary.
Here are my thoughts on it.
What is a container query?
A container query is similar to a CSS media query, except regular media queries can only check the state of the browser window / viewport. Container queries check things like the current width of a HTML element, which opens up a lot of possibilities.
🚨 Disclaimer: I haven't tested these container queries yet, but this is how I think they will impact our developer experience 💯
A use for container queries
Let's say you have a form where the labels of the inputs should be on the left when there is space for it + some other things related to the width of the form.
Not an easy task with regular media (viewport) queries if your form doesn't always span the complete width of the page!
Maybe you can pull it off with things like CSS Flexbox and some smart ways of dealing with wrapping, but maybe you want some other styles to be different when the component becomes smaller.
Especially difficult if you need to "syncronize" multiple style changes based on that wrapping point.
That's currently only possible if you add JS into the mix to check if the width or height changed.
You could then add or remove CSS classes with JS. Not ideal!
Container queries in the component era
Especially in the current "component era" of frontend, it becomes invaluable to be able to scope styles to container size of the component.
Parent layout components no longer need to tweak its children components' CSS in certain scenarios.
And with with ever changing requirements of projects it becomes really handy to define all those styles within the component based on its container size.
Say you make a form component intended to be half the width of the page. Some time passes, and now a colleague has to reuse that component for the full width of another page.
They need to find all the CSS they need to tweak and update that CSS from the parent component.
But let's say the component also needs to be used in other parent components. Now you have to duplicate that full page CSS or find solution to reuse it easily (component composition maybe?)
Way more complex (if you ask me) than defining all those styles within the component!
This post was adapted from my original Twitter thread. Feel free to discuss it there as well!
A thread🧵16:09 PM - 26 Mar 2021
You can subscribe to my newsletter here. It's free!
Top comments (5)
For anyone who wants to play with it here is the codepen that was linked in the original tweet (oviously you need canary latest and to set the flag
calcmagic for me (which is the way we do this now)
Cool cant wait to see this.
Me neither! I can't wait for it to become usable in production. Will probably take a while :(