Responsive CSS Grid Layout with Animation
Inspired by the demo of Bramus, I implemented an animated grid layout. On resize, the elements get a nice animation as they move to their new positions. You can even add or remove items, and everything will adjust smoothly as well.
Try it!
⚠️ (Chromium only for now) ⚠️
See the Pen Animated grid layout on resize by Temani Afif (@t_afif) on CodePen.
The main idea is to calculate the coordinates of each item within the grid, and instead of relying on the automatic placement, I place them using translate. When the layout is updated, all coordinates change, which in turn updates the translate values. We can apply a transition to the translate property to get a nice effect!
.container {
--g: 10px; /* gap */
--s: 130px; /* image size */
display: grid;
container-type: inline-size;
}
.container > * {
grid-area: 1/1;
width: var(--s);
aspect-ratio: 1;
/* The number of columns */
--n: round(down,(100cqw + var(--g))/(var(--s) + var(--g)));
/* The coordinates */
--i: round(down,(sibling-index() - 1)/var(--n));
--j: mod(sibling-index() - 1,var(--n));
translate:
calc(var(--j)*(100% + var(--g)))
calc(var(--i)*(100% + var(--g)));
transition: .4s,scale .3s .4s,opacity .3s .3s,rotate .3s .3s;
/* the entry effect when adding a new item */
@starting-style {
scale: 0;
opacity: 0;
rotate: -1turn;
}
}
More CSS Tips
- Wiggly/Wavy Input Range Slider II Adding a bouncy tooltip to the wiggly slider.
- Responsive Separator for Horizontal List Modern CSS solves a very old design pattern with a few lines of code.