Heydon’s <watched-box>
is a damn fantastic tool. It’s a custom element that essentially does container queries by way of class names that get added to the box based on size breakpoints that are calculated with ResizeObserver
. It’s like a cleaner version of what Philip was talking about a few years ago.
I’m sure I’d be happy using <watched-box>
on production, as it’s lightweight, has no dependencies, and has a straightforward approach.
For development, I had the idea of using Zach’s interesting little <resize-asaurus>
web component. It wraps elements in another box that is resizeable via CSS and labels it with the current width. That way you don’t have to fiddle with the entire browser window to resize things — any given element becomes resizable. Again, just for development and testing reasons.
You’d wrap them together like…
<resize-asaurus>
<watched-box widthBreaks="320px, 600px">
<div class="card">
...
</div>
</watched-box>
</resize-asaurus>
Which allows you to write CSS at breakpoints like…
.card {
.w-gt-320px & { }
.w-gt-600px & { }
}
That’s surely not what the CSS syntax for container queries syntax will end up being, but it accomplishes the same thing with clear and understandable generated class names.
Example!
Live demo!
Love these newer explorations that use ResizeObserver for updating when the element itself updates. It seems like a slightly updated version of my
<style-container>
idea where I was treating each<style-container>
element as its own ‘viewport’, and interpreting any@media
queries inside as though they were element queries based on the dimensions of that<style-container>
element! It’s fun to explore the declarative side of this in HTML too, custom elements like this are a natural fit! https://twitter.com/innovati/status/1086472249660637184The code for watched-box has rooms for improvement. For example, it adds N divs to check the size when N breakpoints exist. I would be quite uncomfortable having 10-20 items that append and remove 2-3 divs every time there’s a change in dimensions.