Perhaps you’ve seen the good news that display: grid-lanes; is starting to arrive in browsers which replicates what we generally call “masonry” layout in CSS. It’s in Safari and feature-flagged in Chrome and Firefox. It gives this staggered grid item layout (with lots of possibilities) reminiscent of a brick wall, hence the name.
The name really comes from David DeSandro’s original library Masonry.js (and also Packery and Isotope). Those libraries accomplished the staggered layout well. But the foundation of them was a bunch of elements floated. Here’s an original demo of Masonry.js:
If you resize that, you’ll see that Masonry.js had another trick up its sleeve: animation!
See, Masonry.js supported fluidity, such that if the number of items (based on an ideal width) that could “fit” on a horizontal row had to change, it would redo its calculation magic and animate the elements into new positions. Here’s a video of that.
I thought about this when I saw a mind-blowing demo from Bramus in which grid items would animate to new positions under the same conditions. But Bramus’ demo uses actual grid layout! And the re-calculating grid was by virtue of repeat/auto-fill magic that grid has always been good at, like grid-template-columns: repeat(auto-fill, 6rem);
The trick in Bramus’ demo is that it’s not actual the grid items themselves that animate into new positions. It’s actually a child element of the grid items, which is set to cover the entire grid area by virtue of anchor positioning and an inset value that tracks the parent cell’s position. Super cool.
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, ...);
.cell {
anchor-scope: --grid-cell;
anchor-name: --grid-cell;
.cell-content {
transition: inset 0.2s ease;
position: absolute;
position-anchor: --grid-cell;
inset: anchor(inside);
}
}
}Code language: CSS (css)
You don’t have to nest it like that; I just did it to make the structure clearer.
That feels pretty darn magical to me. I don’t know I would have thought of it, as it feels like to cover the cell you’d do inset: 0; and then there is nothing really to animate as that never changes. But apparently the anchor(inside) is dynamic enough that it animates even if the end result it essentially the same as inset: 0;
So here’s David’s original demo, with the JavaScript and floating ripped out, and a grid layout put in place instead, with the magical CSS from above:
Here’s a video of that, which is pretty darn close to the same as the JavaScript version.
