Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Masonry Grid for Astro

A responsive Astro masonry layout for cards, images, and other content.

Pink trees in a snowy landscape beneath two planetsClouds around a circular lakeA tall tower surrounded by storm cloudsA lone traveler beside a pink riverA spaceship above an ocean dock

Installation

bunx --bun shadcn@latest add @gnostic/masonry-grid
npx shadcn@latest add @gnostic/masonry-grid
pnpm dlx shadcn@latest add @gnostic/masonry-grid

Complete the Installation guide first. Then copy the component files below.

Install component packages

bun add @data-slot/core

Copy the files

src/components/ui/masonry-grid/index.ts
export { default as MasonryGrid } from './masonry-grid.astro'
export type { MasonryGridProps } from './types.ts'
export { createMasonryGrid } from './masonry-grid.ts'
export type { MasonryGridController } from './masonry-grid.ts'
src/components/ui/masonry-grid/types.ts
/** Layout options for content with different heights. */
export interface MasonryGridProps {
    /**
     * Minimum column count. The layout uses two columns from 30rem and four
     * from 48rem, measured against the component width.
     * @default 1
     */
    minCols?: 1 | 2 | 3 | 4
    /**
     * Space between items as a CSS length.
     * @default '1rem'
     */
    gap?: string
}
src/components/ui/masonry-grid/masonry-grid.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { MasonryGridProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & MasonryGridProps

const {
  minCols = 1,
  gap = "1rem",
  class: className,
  style,
  ...props
} = Astro.props
const columns = {
  1: "grid-cols-1 @min-[30rem]/masonry:grid-cols-2 @min-[48rem]/masonry:grid-cols-4",
  2: "grid-cols-2 @min-[48rem]/masonry:grid-cols-4",
  3: "grid-cols-3 @min-[48rem]/masonry:grid-cols-4",
  4: "grid-cols-4",
}
const mergedStyle =
  typeof style === "string"
    ? `--masonry-gap:${gap};${style}`
    : { "--masonry-gap": gap, ...style }
---

<div
  data-slot="masonry-grid"
  class={cn("@container/masonry block min-w-0", className)}
  style={mergedStyle}
  {...props}
>
  <div
    data-masonry-items
    class={cn(
      "relative grid items-start gap-(--masonry-gap) *:min-w-0 data-[ready]:*:absolute data-[ready]:*:w-(--masonry-width) data-[ready]:*:[inset-inline-start:var(--masonry-x)] data-[ready]:*:[top:var(--masonry-y)]",
      columns[minCols],
    )}
  >
    <slot />
  </div>
</div>

<script>
  import { create } from "./masonry-grid.ts"

  const controllers: ReturnType<typeof create> = []
  const initialize = () => controllers.push(...create())
  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>
src/components/ui/masonry-grid/masonry-grid.ts
import {
    clearRootBinding,
    getRootBinding,
    getRoots,
    hasRootBinding,
    setRootBinding,
} from '@data-slot/core'

export interface MasonryGridController {
    destroy(): void
}

/** Place each item in the shortest column without changing DOM order. */
export function createMasonryGrid(root: HTMLElement): MasonryGridController {
    const existing = getRootBinding<MasonryGridController>(
        root,
        '@gnostic/masonry-grid',
    )
    if (existing) return existing
    const grid = root.querySelector<HTMLElement>(
        ':scope > [data-masonry-items]',
    )
    let destroyed = false
    let frame = 0
    let items: HTMLElement[] = []
    const resetItem = (item: HTMLElement) => {
        item.style.removeProperty('--masonry-x')
        item.style.removeProperty('--masonry-y')
    }
    const layout = () => {
        frame = 0
        if (destroyed || !grid || grid.clientWidth === 0) return
        const styles = getComputedStyle(grid)
        const tracks = styles.gridTemplateColumns.split(' ')
        const width = Number.parseFloat(tracks[0] ?? '')
        if (!Number.isFinite(width) || width <= 0) return
        const gap = Number.parseFloat(styles.columnGap) || 0
        const heights = Array<number>(tracks.length).fill(0)
        grid.style.setProperty('--masonry-width', `${width}px`)
        grid.dataset.ready = ''
        const sizes = items.map((item) => item.getBoundingClientRect().height)
        items.forEach((item, index) => {
            if (getComputedStyle(item).display === 'none') return
            const column = heights.indexOf(Math.min(...heights))
            item.style.setProperty('--masonry-x', `${column * (width + gap)}px`)
            item.style.setProperty('--masonry-y', `${heights[column]}px`)
            heights[column] += sizes[index]! + gap
        })
        grid.style.height = `${Math.max(0, ...heights) > 0 ? Math.max(...heights) - gap : 0}px`
    }
    const schedule = () => {
        if (!destroyed && !frame) frame = requestAnimationFrame(layout)
    }
    const resize = new ResizeObserver(schedule)
    const observeItems = () => {
        if (destroyed) return
        for (const item of items) {
            resize.unobserve(item)
            resetItem(item)
        }
        items = Array.from(grid?.children ?? []).filter(
            (child): child is HTMLElement => child instanceof HTMLElement,
        )
        for (const item of items) resize.observe(item)
        schedule()
    }
    const mutation = new MutationObserver(observeItems)
    if (grid) {
        resize.observe(grid)
        mutation.observe(grid, { childList: true })
        observeItems()
    }
    const controller: MasonryGridController = {
        destroy() {
            if (destroyed) return
            destroyed = true
            cancelAnimationFrame(frame)
            resize.disconnect()
            mutation.disconnect()
            if (grid) {
                delete grid.dataset.ready
                grid.style.removeProperty('height')
                grid.style.removeProperty('--masonry-width')
            }
            items.forEach(resetItem)
            items = []
            clearRootBinding(root, '@gnostic/masonry-grid', controller)
        },
    }
    return setRootBinding(root, '@gnostic/masonry-grid', controller)
}

export function create(scope: ParentNode = document): MasonryGridController[] {
    return getRoots<HTMLElement>(scope, 'masonry-grid')
        .filter((root) => !hasRootBinding(root, '@gnostic/masonry-grid'))
        .map(createMasonryGrid)
}

Usage

---
import { Image } from "astro:assets"
import { MasonryGrid } from "@/components/ui/masonry-grid"
import landscape from "@/assets/images/winter-landscape-theta.png"
import clouds from "@/assets/images/clouds-around-water.png"
---

<MasonryGrid gap="0.75rem">
  <Image
    src={landscape}
    alt="Pink trees in a snowy landscape beneath two planets"
    width={640}
    height={800}
    fit="cover"
    class="h-auto w-full rounded-lg"
  />
  <Image
    src={clouds}
    alt="Clouds around a circular lake"
    width={640}
    height={400}
    fit="cover"
    class="h-auto w-full rounded-lg"
  />
</MasonryGrid>

Use different image heights to show the offset columns. This example crops the images to portrait, square, and landscape shapes. Keep h-auto w-full on each image so its displayed height follows its dimensions. The top example uses at most two columns. Its final image crop accounts for the extra gap in the right column, so both columns end at the same height.

Each direct child is one item. Use a wrapper when several elements belong to one item. Cards, images, links, and other Astro components can use the same layout. Items keep their natural height. Use gap for spacing between items; keep outer margins and position styles off the item roots.

The component places each item in the shortest column. Equal columns fill from the inline start, including in right-to-left layouts. The script measures items again when the container, an image, or other content changes size. It also handles items added to or removed from the slot container.

The default is one column below 30rem, two from 30rem, and four from 48rem. These widths refer to the component container. minCols sets a lower limit. Use the preview width controls to check a smaller container.

Cards

Cards with different amounts of content use the same layout. Each card keeps its natural height.

Field notes
Monday

Follow the path beside the river. The old bridge is a good place to stop and draw. Take paper, a pencil, and a small camera. Leave room in the notebook for the plants you find along the way.

A small idea
Tuesday

Make one drawing each day.

Things to collect
Wednesday

Look for shapes in leaves, stones, and clouds. Record their colors. Use the notes to make a set of small prints when you return.

Next walk
Thursday

Start at the north gate. Follow the trail to the lake.

At the workshop
Friday

Put the drawings on a large table. Choose three that work well together. Try different paper sizes, then compare the results in daylight. Keep the first set for reference.

Keep it simple
Saturday

A pencil and a blank page are enough.

Images with lightboxes

Use LightboxGridItem inside MasonryGrid. Keep h-auto w-full on each thumbnail so its height follows its dimensions. The lightbox example uses different thumbnail crops; each dialog shows the full source image.

See the masonry lightbox example.

LightboxGrid layout="masonry" uses this same component internally.

Reading order and fallback

Source order stays unchanged for keyboard and screen reader access. Visual positions depend on item height. Use a normal grid for content that must read in strict rows. Without JavaScript, items use a responsive grid with natural heights. Supply image dimensions to reduce layout movement during loading.

API Reference

MasonryGrid accepts native div attributes and a default slot. Use class for the outer container. Use style to override --masonry-gap.

MasonryGridProps

PropType
minCols?1 | 2 | 3 | 4

Minimum column count. The layout uses two columns from 30rem and four from 48rem, measured against the component width.

Type1 | 2 | 3 | 4
Default1
gap?string

Space between items as a CSS length.

Typestring
Default'1rem'

The registry source includes the Astro component and its browser script.

Theme and layout

Use the outer class for page width and spacing. Set the gap through the component prop or the --masonry-gap variable. Keep outer margins and positioning off the item roots so measurements stay accurate. Place Card or Lightbox content inside the grid, and check the reading order at each width.

The root is a normal HTML element. The component attaches its factory on script load and astro:page-load, then calls destroy() before an Astro page swap. For direct DOM changes, import createMasonryGrid from the component index. Destroy the returned controller before removing the root.