Great work by Heydon Pickering, in which he lets a flexbox layout respond to the size of its container, and not the viewport
Sometimes you want your items to wrap in a very particular way. For instance, when you have three items, you’ll be happy with the three-abreast layout and accepting of the single-column configuration. But you might like to avoid the intermediary part where you get a pair of elements on one line followed by a longer element underneath.
How do we skip this intermediary layout state and switch directly from a horizontal to vertical triptych? What’s the solution?
The solution he knocked up involves
flex-basis being changed thanks to
calc() and CSS Custom Properties (“CSS Variables”). The code behaves nicely when the viewport becomes too narrow, or when the container becomes too narrow (set the
max-width of the
37em to see it in action)
💁♂️ To get a good understanding of how exactly this works, see Jonathan Snook’s Understanding the Albatross
Now, are these “Container Queries” we want? Not quite imho: whilst is does tackle the issue of layout for flexed children, it’s still not possible to, for example, change the
font-size or, another example, switch from
grid using this technique.
Sidenote: I think one could hack the
font-size thing together if CSS
calc() were to support the modulo operator, but that’s not the case unfortunately. Also, it would still leave switching from
grid out of the loop.
Related: Conditions for CSS Calculations →