Masonry-style layouts with CSS grid

Using CSS grid layout to lay out items automatically, masonry-style

Masonry-style layouts with CSS grid

I've struggled to get the hype for CSS grid for the most part. The CSS syntax seems slightly odd; explicitly positioning each element on a template grid by defining the grid positioning in CSS has always felt brittle.

I finally looked into it in more detail when designing a training course for Front-end Web Development using our internal CMS here at the University of Warwick. After a few attempts to design examples for an exercise that explicitly positioned elements within a grid, I then went to design one that relies on a browser auto-positioning elements.

The idea was to replicate a quite common design used to good effect on the University of Warwick's staff intranet, insite - a boxed layout with various sizes of box that fall into rows with consistent spacing between. The current implementation uses the Bootstrap grid system, with JavaScript used to reposition boxes on reflows. Ick.

CSS grid is perfect for this because we can individually set the sizes of the boxes, then rely on grid-auto-flow: row dense; so that the browser positions boxes in gaps if they'd fit. We can still override positioning of individual boxes as necessary, but we can use masonry-style behaviour so the browser is responsible for positioning the boxes to best utilise the available space.