---
title: Masonry Grid for Astro
description: "A responsive Astro masonry layout for cards, images, and other content."
sidebar:
    label: "Masonry Grid"
    badge: new
seo:
    title: Masonry Grid for Astro | Shadcn & Tailwind CSS
related:
    - /components/lightbox-grid
    - /components/card
---

```astro
---
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"
import storm from "@/assets/images/futuristic-storm.png"
import journey from "@/assets/images/solo-journey.png"
import spaceship from "@/assets/images/spaceship-docking-in-ocean.png"

const images = [
  {
    src: landscape,
    alt: "Pink trees in a snowy landscape beneath two planets",
    height: 800,
  },
  { src: clouds, alt: "Clouds around a circular lake", height: 400 },
  { src: storm, alt: "A tall tower surrounded by storm clouds", height: 640 },
  { src: journey, alt: "A lone traveler beside a pink river", height: 880 },
  { src: spaceship, alt: "A spaceship above an ocean dock", height: 640 },
]
---

<div class="mx-auto w-full max-w-2xl p-4">
  <MasonryGrid gap="0.75rem">
    {images.map((image) => (
      <Image
        {...image}
        width={640}
        widths={[320, 640, 960]}
        sizes="auto, 100vw"
        fit="cover"
        class="block h-auto w-full rounded-lg object-cover @min-[30rem]/masonry:last:h-[calc(var(--masonry-width)-var(--masonry-gap))]"
        loading="lazy"
      />
    ))}
  </MasonryGrid>
</div>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/masonry-grid
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

Install the component packages:

```sh
bun add @data-slot/core
```

#### src/components/ui/masonry-grid/index.ts

```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

```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

```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

```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)
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

```astro
---
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.

```astro
---
import { MasonryGrid } from "@/components/ui/masonry-grid"
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
} from "@/components/ui/card"

const notes = [
  {
    title: "Field notes",
    label: "Monday",
    text: "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.",
  },
  {
    title: "A small idea",
    label: "Tuesday",
    text: "Make one drawing each day.",
  },
  {
    title: "Things to collect",
    label: "Wednesday",
    text: "Look for shapes in leaves, stones, and clouds. Record their colors. Use the notes to make a set of small prints when you return.",
  },
  {
    title: "Next walk",
    label: "Thursday",
    text: "Start at the north gate. Follow the trail to the lake.",
  },
  {
    title: "At the workshop",
    label: "Friday",
    text: "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.",
  },
  {
    title: "Keep it simple",
    label: "Saturday",
    text: "A pencil and a blank page are enough.",
  },
]
---

<div class="w-full p-4">
  <MasonryGrid>
    {notes.map((note) => (
      <Card>
        <CardHeader>
          <CardTitle>{note.title}</CardTitle>
          <CardDescription>{note.label}</CardDescription>
        </CardHeader>
        <CardContent>
          <p>{note.text}</p>
        </CardContent>
      </Card>
    ))}
  </MasonryGrid>
</div>
```

## 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](/components/lightbox-grid#masonry-and-resizing).

`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

<AutoTypeTable
    path="../../packages/ui/src/components/ui/masonry-grid/types.ts"
    name="MasonryGridProps"
/>

The [registry source](/r/masonry-grid.json) 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](/components/card) or [Lightbox](/components/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.
