Container Queries, as in, the ability to style elements based on values from a particular element, like its width and height. We have media queries, but those are based on the viewport not individual elements. There are plenty of use cases for them. It’s been said before, but I’ll say it again, if container queries existed, the vast majority of media queries in CSS would actually be container queries.
Discussion about how to pull it off technologically gets interesting. In my mind, ideally, we get this ability right in CSS. The trouble with doing it this way is one of circularity. Not even in regards to being able to write CSS that triggers a scenario in which the query doesn’t match anymore, which is tricky enough, but literally changing the long-standing single-pass way in which browsers render a page.
— CSS-Tricks (@Real_CSS_Tricks) February 1, 2018
ResizeObserver. It’s Chrome-only as I write, but here’s a chart that should stay updated in time:
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Mobile / Tablet
|Android Chrome||Android Firefox||Android||iOS Safari|
That was a heck of a lot of words to intro the fact that Philip Walton just wrote a hell of an article about doing just this. The core of it is that you use ResizeOveserver to toss classes onto elements, then style them with those classes. He concludes:
The strategy outlined in this article:
- Will work, today, on any website
- Is easy to implement (copy/paste-able)
- Performs just as well as a CSS-based solution
- Doesn’t require any specific libraries, frameworks, or build tools.
The browser support for
ResizeObserver is a little scary, but it’s such a nice API I would expect more widespread support sooner than later.