How it works
Unlike CSS columns, which fill top to bottom, each card goes to the top of the shortest column in turn, so the first cards stay at the top. Cards keep their DOM order and are placed with transforms from measured heights; a ResizeObserver remeasures when images load or text wraps. Before measuring (on the server and in the first frame) the grid falls back to a plain auto-fill grid, so it never renders empty.
Use it for
- Galleries, moodboards and pins with mixed aspect ratios.
- Cards whose text lengths vary a lot, such as notes or reviews.
Look elsewhere when
- Items that must line up in rows for comparison: use a regular grid or table.
- Thousands of items: pair it with paging, or use a virtual list.
Usage
import { MasonryGrid } from './MasonryGrid.jsx'
export function Gallery({ photos }) {
return (
<MasonryGrid
label="Photos"
items={photos}
getKey={(p) => p.id}
minColumnWidth={180}
maxColumns={4}
renderItem={(p) => <img src={p.src} alt={p.alt} width={p.width} height={p.height} style={{ width: '100%', height: 'auto' }} />}
/>
)
}Props
| Prop | Type | Default | What it does |
|---|---|---|---|
items | T[] | — | The data, in reading order. |
renderItem | (item: T, index) => ReactNode | — | Renders one card at the column width; its height can be anything. |
getKey | (item: T, index) => Key | item.id ?? index | A stable key, so a card keeps its measured height and glides instead of reappearing. |
minColumnWidth | number | 180 | Columns are added while each stays at least this wide. |
maxColumns | number | 4 | Upper limit on columns. |
gap | number | 12 | Space between cards in px, both ways. |
label | string | — | Accessible name of the list. |
...rest | HTMLAttributes<HTMLDivElement> | — | Passed to the root. |
Accessibility
- The root is role="list" and each card a listitem; DOM order equals data order, so screen readers and Tab follow the reading order, not the columns.
- Focusable content inside cards keeps its own focus styles; the grid adds no keyboard traps.
- Reduced motion removes the glide between layouts and shortens the fade-in to 160ms.
Motion
Cards fade in 40ms apart (up to twelve). When columns or heights change, cards move on a 560ms decelerating curve (cubic-bezier(0.2, 0.9, 0.25, 1)) and the grid height follows.
Add it to your project
Copy the prompt into Codex or Claude Code. The agent reads the published source, shows you what it will write and adds the component next to your own.
MasonryGrid.jsxmasonry-grid.csstokens.cssREADME.md
Both files install together. The stylesheet reads the design tokens in tokens.css and carries fallbacks, so it also works alone.



