Migrating from Masonry
Masonry, the masonry-layout package and its masonry.pkgd.min.js script, is the classic masonry library and a jQuery plugin. Its last release, 4.2.2, came out in July 2018, and the approach shows its age. Masonry measures every item and positions it absolutely, so items overlap until their images load, a second script, imagesLoaded, has to lay the grid out again, and every change of an item’s size needs a layout() call.
Masonry Grid leaves the placing to the browser. The container is a CSS Grid, every frame declares its aspect ratio, and the layout is computed from the ratios before a single image loads:
- No overlapping items. A frame has its final size before its image arrives, so the grid is right without imagesLoaded.
- No
layout()calls. The grid follows its container and its children by itself: add, remove or resize frames and it lays them out again. - No jQuery. One line of plain JavaScript, or ready components for React, Preact, Svelte, SolidJS and Nanoviews.
- A quarter of the size.
@masonry-grid/vanillais 1.6 kB with brotli.masonry.pkgd.min.jsis 6.6 kB, before you add imagesLoaded. - Columns that fill the container. No empty space on the right and no
fitWidthto center the grid.
Before and After
Section titled “Before and After”A grid of photos with Masonry and imagesLoaded:
<style> .grid-item { width: 200px; margin-bottom: 10px; }</style>
<div class="grid"> <div class="grid-item"><img src="photo-1.jpg" alt="Photo 1" /></div> <div class="grid-item"><img src="photo-2.jpg" alt="Photo 2" /></div> <!-- more items... --></div>
<script type="module"> import Masonry from 'masonry-layout' import imagesLoaded from 'imagesloaded'
const grid = document.querySelector('.grid') const msnry = new Masonry(grid, { itemSelector: '.grid-item', columnWidth: 200, gutter: 10 })
imagesLoaded(grid).on('progress', () => { msnry.layout() })</script>The same grid with Masonry Grid:
<style> .grid { display: grid; overflow: hidden; gap: 10px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
.grid-item { aspect-ratio: var(--width) / var(--height); }
.grid-item img { width: 100%; }</style>
<div class="grid"> <div class="grid-item" style="--width: 4; --height: 3"><img src="photo-1.jpg" alt="Photo 1" /></div> <div class="grid-item" style="--width: 2; --height: 3"><img src="photo-2.jpg" alt="Photo 2" /></div> <!-- more items... --></div>
<script type="module"> import { BalancedMasonryGrid } from '@masonry-grid/vanilla'
new BalancedMasonryGrid(document.querySelector('.grid'))</script>What changed:
- The container is a CSS Grid. The columns are at least 200px wide and stretch to fill the container.
- Every frame sets
--widthand--heightin itsstyleattribute, and Masonry Grid reads the aspect ratio from there. Any pair with the right ratio works, such as the pixel size of the image. - imagesLoaded and the
layout()calls are gone, along with the options object.
Prerequisites lists the styles that the container and the frames need.
Options
Section titled “Options”Most options of Masonry exist to work around measuring and absolute positioning. With CSS Grid, they turn into plain CSS or are not needed at all.
| Masonry | Masonry Grid |
|---|---|
itemSelector |
Not needed: every child of the container is a frame. |
columnWidth |
The minimum column width in grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)), or the frameWidth prop of the framework components. |
gutter and the margin of items |
CSS gap, one property for both columns and rows. |
percentPosition |
Not needed: frames are moved with translateY in percent of their own height, so the layout scales with the container. |
horizontalOrder: true |
RegularMasonryGrid: frames keep the source order, and every frame stays in its column of the grid. |
| Default placement in the shortest column | BalancedMasonryGrid: reorders frames inside each row to even out the columns, while the DOM keeps the source order. |
fitWidth |
Not needed: 1fr columns fill the container. |
resize |
Always on, and better: a ResizeObserver watches the container itself, not only the window. |
initLayout: false |
Not needed: there are no events to bind before the first layout. |
transitionDuration, stagger |
Not needed: frames take their place at once. |
stamp |
No equivalent. |
Balanced vs Regular shows both layouts side by side.
Methods and Events
Section titled “Methods and Events”Most methods of Masonry tell it about changes it cannot see. Masonry Grid sees them by itself, so there is nothing to call.
| Masonry | Masonry Grid |
|---|---|
layout() |
Not needed: the grid lays out again when the container resizes or its children change. |
appended(), prepended(), addItems(), remove(), reloadItems() |
Not needed: change the DOM as usual. A MutationObserver picks up added and removed frames and changes of their style. |
destroy() |
destroy() removes the observers and the styles that the grid has set. |
Masonry.data(element) |
Keep the instance that new returns. |
layoutComplete, removeComplete |
Not needed: there are no transitions to wait for. |
The infinite scroll example appends frames to the container without calling anything on the grid.
Goodbye, imagesLoaded
Section titled “Goodbye, imagesLoaded”Masonry measures the items, and an image that has not loaded yet has no height, so items overlap until the next layout(). Masonry’s docs pair it with imagesLoaded for this reason, and web fonts or embeds cause the same overlap.
Masonry Grid does not measure anything. A frame takes its final size from its aspect ratio before the image arrives, so the layout is right from the start and nothing moves when the images load. Remove imagesLoaded together with the layout() calls, and the page no longer shifts as images load.
From jQuery to One Line
Section titled “From jQuery to One Line”Masonry Grid needs no jQuery plugin and no data-masonry attribute. Create the grid in a module script:
// Before$('.grid').masonry({ itemSelector: '.grid-item', columnWidth: 200 })
// Afternew BalancedMasonryGrid(document.querySelector('.grid'))Masonry Grid is an ES module. In place of a <script src="masonry.pkgd.min.js"> tag, load it from a CDN inside <script type="module">:
import { BalancedMasonryGrid } from 'https://esm.sh/@masonry-grid/vanilla@1'With React, Preact, Svelte, SolidJS or Nanoviews, use their components from Getting Started and drop the wrapper you used around Masonry. React Masonry Libraries Compared shows why the React wrapper of Masonry is worth leaving too.
Ready to Switch
Section titled “Ready to Switch”- Give every frame its aspect ratio. Images already have one: a CMS or an image API returns their size, and you know it when you upload a file. Setting it up front is what keeps any page from shifting as images load, and Masonry Grid lays out the whole grid from it.
- Target current browsers. Masonry Grid builds on CSS Grid, the
aspect-ratioproperty andResizeObserver, which every current browser supports. Masonry 4 supports browsers as old as Internet Explorer 10, and Microsoft retired Internet Explorer in 2022.