Tools: Open Source Solving Shrinkwrap: New Experimental Technique
In this article, I present my new technique for solving a CSS problem that was deemed impossible — true shrinkwrapping of an element with auto-wrapped content. By using anchor positioning and scroll-driven animations, we can adjust our element’s outer dimensions by measuring its inner contents, demonstrating that for many cases this can already work and might unlock a future native feature.
Since anchor positioning and scroll-driven animations appeared on my radar, I knew they would unlock things that were not possible before. These new CSS features hook into many things that were previously either impossible or available only through cumbersome JavaScript APIs. Two years ago, I wrote about one of such things — the “shrinkwrap” problem and a partial decorative workaround that used anchor positioning — in my “The Shrinkwrap Problem: Possible Future Solutions” article.
After writing that article, and experimenting more with scroll-driven animations, I knew that there could be a way to combine those and achieve shrinkwrapping not just visually, but also make it affect the layout. In the last few months, I was experimenting with my past findings and a few novel approaches, and, finally, honed them into something reusable — and already working in stable Chrome and Safari, with a graceful degradationGo to a sidenote for other browsers.
That said, even though my examples for the base technique might work in the latest versions of some stable browsers, the technique itself is highly experimental.
For example, I experienced occasional crashes in Safari. I managed to find a workaround, but I strongly suggest being careful before using anything from this article in production.
Let’s say we have a simple header, which we style to look like a nice rounded box, and that should shrink to its max-content:
When it is short, all is good! But we anticipate that it might wrap when the content is longer, and add text-wrap: balance to make it prettier. But then, this happens:
On most viewports, you could see how when the header wraps, we get all this extra space on one side — the shrinkwrap problem. What exactly is happening, and why is it so challenging to make it work?
When different content wraps — be it text, floats, inline-blocks, flex, or grid, — if that wrapping is automatic (without hard breaks), the way CSS calculates the final width is limited. The element with wrapped items gets expanded to fill all the available space.
In CSS2 specs, this behavior is called
Source: HackerNews