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.

https://platform.twitter.com/widgets.js

There are plenty of takes at solving this. All JavaScript of course. Dave Rupert rounded some of them up here. They are all a bit different.

Seems to me the most well-suited JavaScript API for this is 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.

Desktop

ChromeOperaFirefoxIEEdgeSafari
64NoNoNoNoNo

Mobile / Tablet

iOS SafariOpera MobileOpera MiniAndroidAndroid ChromeAndroid Firefox
NoNoNoNoNoNo

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.
  • Leverages progressive enhancement, so users on browser that lack the required APIs or have JavaScript disabled can still use the site.

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.

Direct Link to ArticlePermalink


Responsive Components: a Solution to the Container Queries Problem is a post from CSS-Tricks