---
title: Lightbox Grid for Astro
description: "Responsive Astro gallery grids with normal grid, bento, and masonry layouts."
sidebar:
    label: "Lightbox Grid"
    badge: new
seo:
    title: Lightbox Grid for Astro | Shadcn & Tailwind CSS
related:
    - /components/lightbox
    - /components/bento-grid
    - /components/masonry-grid
    - /components/lightbox-carousel
---

The default grid fills each row. On a wide screen, these six images form two
rows of three. Select a thumbnail to open the full image.

```astro
---
import { LightboxGrid, LightboxGridItem } from "@/components/ui/lightbox-grid"

const images = [
  {
    src: "https://images.unsplash.com/photo-1470770841072-f978cf4d019e?w=1200&h=800&auto=format&fit=crop",
    width: 1200,
    height: 800,
    alt: "Mountains reflected in a lake",
    caption: "A quiet mountain lake.",
  },
  {
    src: "https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=1200&h=800&auto=format&fit=crop",
    width: 1200,
    height: 800,
    alt: "Sunlight through forest trees",
  },
  {
    src: "https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=1200&h=800&auto=format&fit=crop",
    width: 1200,
    height: 800,
    alt: "Open landscape in evening light",
  },
  {
    src: "https://images.unsplash.com/photo-1464822759023-fed622ff2c3b?w=1200&h=800&auto=format&fit=crop",
    width: 1200,
    height: 800,
    alt: "A mountain peak above the clouds",
  },
  {
    src: "https://images.unsplash.com/photo-1472396961693-142e6e269027?w=1200&h=800&auto=format&fit=crop",
    width: 1200,
    height: 800,
    alt: "Deer in a green forest",
  },
  {
    src: "https://images.unsplash.com/photo-1447752875215-b2761acb3c5d?w=1200&h=800&auto=format&fit=crop",
    width: 1200,
    height: 800,
    alt: "A path through tall trees",
  },
]
---

<div class="w-full p-4">
  <LightboxGrid rowHeight="10rem">
    {images.map(({ caption, ...image }) => (
      <LightboxGridItem image={image} caption={caption} />
    ))}
  </LightboxGrid>
</div>
```

## Installation

### Command

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

### Manual

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

No extra packages are required.

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

```ts
export { default as LightboxGrid } from './lightbox-grid.astro'
export { default as LightboxGridItem } from './lightbox-grid-item.astro'
export type { LightboxGridProps, LightboxGridItemProps } from './types.ts'
```

#### src/components/ui/lightbox-grid/types.ts

```ts
import type { LightboxItemImage } from '@/components/ui/lightbox/types.ts'

export interface LightboxGridProps {
    /**
     * Full rows of equal-height tiles, mixed bento spans, or natural-height masonry items.
     * @default 'grid'
     */
    layout?: 'grid' | 'bento' | 'masonry'
    /**
     * Minimum column count. Use a positive integer.
     *
     * @default 1
     */
    minCols?: number
    /**
     * Minimum row count for grid and bento. Use a positive integer.
     *
     * @default 1
     */
    minRows?: number
    /**
     * The height of each row in the grid as a CSS value
     *
     * @default '14rem' // 224px
     */
    rowHeight?: string
    /**
     * A valid CSS gap value
     *
     * @default '0.5rem'
     */
    gap?: string
}

/** One image in the gallery. */
export interface LightboxGridItemProps {
    /** Shared image source and description, with optional Astro Image props for each view. */
    image: LightboxItemImage
    /** Show this text below the image in a dialog. Omit it for image zoom. */
    caption?: string
    /** Number of cells the tile occupies in a bento grid. */
    span?: 'auto' | 'square' | 'wide' | 'tall' | 'large'
    /**
     * Scale the thumbnail on hover.
     * The preview uses `hover:scale-105`.
     *
     * @default true
     */
    hoverZoom?: boolean
}
```

#### src/components/ui/lightbox-grid/lightbox-grid.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

import { MasonryGrid } from "@/components/ui/masonry-grid"

import type { LightboxGridProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & LightboxGridProps

const {
  layout = "grid",
  minCols = 1,
  minRows = 1,
  rowHeight = "14rem",
  gap = "0.5rem",
  class: className,
  style,
  ...props
} = Astro.props

if (!Number.isSafeInteger(minCols) || minCols < 1) {
  throw new RangeError("LightboxGrid minCols must be a positive integer.")
}
if (!Number.isSafeInteger(minRows) || minRows < 1) {
  throw new RangeError("LightboxGrid minRows must be a positive integer.")
}
// Six tracks can hold three equal tiles or two equal tiles in a row.
// Twelve tracks also allow four equal tiles when the caller requests them.
const gridColumns: Record<number, string> = {
  1: "grid-cols-1 @min-sm/lightbox-grid:grid-cols-2 @min-sm/lightbox-grid:[container-name:lightbox-pairs] @min-lg/lightbox-grid:grid-cols-6 @min-lg/lightbox-grid:[container-name:lightbox-triples]",
  2: "grid-cols-2 [container-name:lightbox-pairs] @min-lg/lightbox-grid:grid-cols-6 @min-lg/lightbox-grid:[container-name:lightbox-triples]",
  3: "grid-cols-6 [container-name:lightbox-triples]",
  4: "grid-cols-12 [container-name:lightbox-quads]",
}
const variables = {
  "--lightbox-grid-row-height": rowHeight,
  "--lightbox-grid-gap": gap,
  ...(layout === "bento" && {
    "--lightbox-bento-cols": minCols,
    "--lightbox-bento-rows": minRows,
  }),
}
// Preserve CSS values that contain colons or semicolons.
const mergedStyle =
  typeof style === "string"
    ? Object.entries(variables)
        .map(([key, value]) => `${key}:${value};`)
        .join("") + style
    : { ...variables, ...style }
---

<div
  data-slot="lightbox-grid"
  data-lightbox-layout={layout}
  class={cn(
    "@container/lightbox-grid",
    layout === "bento" &&
      "grid grid-flow-dense auto-rows-(--lightbox-grid-row-height) grid-cols-[repeat(auto-fill,minmax(var(--lightbox-bento-track),1fr))] grid-rows-[repeat(var(--lightbox-bento-rows),var(--lightbox-grid-row-height))] gap-(--lightbox-grid-gap)",
    className,
  )}
  style={mergedStyle}
  {...props}
>
  {layout === "bento" ? (
    <slot />
  ) : layout === "masonry" ? (
    <MasonryGrid minCols={minCols} gap="var(--lightbox-grid-gap)">
      <slot />
    </MasonryGrid>
  ) : minCols > 4 ? (
    <div
      data-lightbox-wrap
      class="flex flex-wrap content-start gap-(--lightbox-grid-gap)"
      style={`--lightbox-cols:${minCols};min-height:calc(${minRows} * var(--lightbox-grid-row-height) + ${minRows - 1} * var(--lightbox-grid-gap))`}
    >
      <slot />
    </div>
  ) : (
    <div
      class={cn(
        "grid auto-rows-(--lightbox-grid-row-height) gap-(--lightbox-grid-gap)",
        "[container-type:inline-size]",
        gridColumns[minCols],
      )}
      data-lightbox-rows
      style={`grid-template-rows:repeat(${minRows},var(--lightbox-grid-row-height))`}
    >
      <slot />
    </div>
  )}
</div>

<style is:global>
  [data-lightbox-layout="bento"] {
    /* Two default tracks fit at 24rem. Smaller tracks can satisfy minCols. */
    --lightbox-bento-track: min(
      calc((24rem - var(--lightbox-grid-gap)) / 2),
      calc(
        (100% + var(--lightbox-grid-gap)) / var(--lightbox-bento-cols) -
          var(--lightbox-grid-gap)
      )
    );
  }

  /* Let each incomplete row share its remaining width without a track map. */
  [data-lightbox-wrap] > [data-lightbox-span] {
    flex: 1 1
      calc(
        (100% + var(--lightbox-grid-gap)) / var(--lightbox-cols) -
          var(--lightbox-grid-gap)
      );
    height: var(--lightbox-grid-row-height);
  }

  /* Each LightboxGridItem renders one div. Count its siblings of the same
     type so a script between two tiles does not affect their placement. */
  @container lightbox-pairs (min-width: 0px) {
    [data-lightbox-rows] > [data-lightbox-span]:last-of-type:nth-of-type(odd) {
      grid-column: 1 / -1;
    }
  }

  @container lightbox-triples (min-width: 0px) {
    [data-lightbox-rows] > [data-lightbox-span] {
      grid-column: span 2;
    }

    /* A remainder of one becomes two pairs. A remainder of two is one pair. */
    [data-lightbox-rows]:has(
        > [data-lightbox-span]:last-of-type:nth-of-type(3n + 4)
      )
      > [data-lightbox-span]:nth-last-of-type(-n + 4),
    [data-lightbox-rows]:has(
        > [data-lightbox-span]:last-of-type:nth-of-type(3n + 2)
      )
      > [data-lightbox-span]:nth-last-of-type(-n + 2) {
      grid-column: span 3;
    }
  }

  @container lightbox-quads (min-width: 0px) {
    [data-lightbox-rows] > [data-lightbox-span] {
      grid-column: span 3;
    }

    [data-lightbox-rows]:has(
        > [data-lightbox-span]:last-of-type:nth-of-type(4n + 3)
      )
      > [data-lightbox-span]:nth-last-of-type(-n + 3) {
      grid-column: span 4;
    }

    [data-lightbox-rows]:has(
        > [data-lightbox-span]:last-of-type:nth-of-type(4n + 2)
      )
      > [data-lightbox-span]:nth-last-of-type(-n + 2) {
      grid-column: span 6;
    }

    [data-lightbox-rows]
      > [data-lightbox-span]:last-of-type:nth-of-type(4n + 1) {
      grid-column: 1 / -1;
    }
  }

  [data-lightbox-rows] > [data-lightbox-span]:only-of-type {
    grid-column: 1 / -1;
  }
</style>
```

#### src/components/ui/lightbox-grid/lightbox-grid-item.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { Image } from "astro:assets"
import { cn } from "cn"

import {
  Lightbox,
  LightboxContent,
  LightboxImage,
  LightboxTrigger,
} from "@/components/ui/lightbox"
import { getLightboxImages } from "@/components/ui/lightbox/lightbox-item-images.ts"

import type { LightboxGridItemProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & LightboxGridItemProps

const {
  image,
  caption,
  class: className,
  hoverZoom = true,
  span = "auto",
  ...props
} = Astro.props

const hasCaption = Boolean(caption?.trim())
const Root = hasCaption ? Lightbox : "div"
const { preview, enlarged } = getLightboxImages(
  image,
  hasCaption ? "dialog" : "zoom",
)
const thumbnailClass = cn(
  "block h-auto w-full object-cover in-data-[lightbox-layout=bento]:h-full in-data-[lightbox-layout=grid]:h-full",
  preview.class,
)
---

<Root
  class={cn(
    "min-h-0 min-w-0",
    (span === "tall" || span === "large") &&
      "in-data-[lightbox-layout=bento]:@sm/lightbox-grid:row-span-2",
    (span === "wide" || span === "large") &&
      "in-data-[lightbox-layout=bento]:@sm/lightbox-grid:col-span-2",
    !hasCaption &&
      "has-focus-visible:outline-ring overflow-hidden rounded-xl has-focus-visible:outline-2 has-focus-visible:outline-offset-3",
    className,
  )}
  data-lightbox-span={span}
  {...props}
>
  {hasCaption ? (
    <>
      <LightboxTrigger
        hoverZoom={hoverZoom}
        class="w-full in-data-[lightbox-layout=bento]:h-full in-data-[lightbox-layout=grid]:h-full"
        aria-label={`View image: ${image.alt}`}
      >
        <Image {...preview} class={thumbnailClass} />
      </LightboxTrigger>
      <LightboxContent label={image.alt} caption={caption}>
        <Image {...enlarged} />
      </LightboxContent>
    </>
  ) : (
    <LightboxImage
      {...preview}
      zoomImage={image.content ? enlarged : undefined}
      class={cn(
        thumbnailClass,
        hoverZoom &&
          "motion-safe:transition-transform motion-safe:duration-300 motion-safe:hover:scale-105",
      )}
    />
  )}
</Root>
```

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

Pass one `image` object to each `LightboxGridItem`. Both views use its source
and alt text. Select an image to zoom in. Add a `caption` to open the image
and its caption in a dialog.

```astro
---
import { LightboxGrid, LightboxGridItem } from "@/components/ui/lightbox-grid"
import lake from "../assets/lake.jpg"

const images = [{ src: lake, alt: "Mountains reflected in a lake" }]
---

<LightboxGrid>
    {images.map((image) => <LightboxGridItem image={image} />)}
</LightboxGrid>
```

To migrate an existing item, move its `alt` to `image.alt` and move the two
named slots’ image props to `image.thumbnail` and `image.content`.

### Thumbnail and enlarged image

The grid uses `object-cover` to crop the thumbnail inside its tile. With no
caption or `image.content` override, the item renders one image. On zoom,
`LightboxImage` uses the same source and responsive candidates with `sizes="90vw"`.
The enlarged image keeps the source aspect ratio.

Set CSS classes on `image.thumbnail` to control the crop. For example, this
masonry tile shows a square thumbnail with the top of the photo in view.

```astro
<LightboxGridItem image={{
    src: lake,
    alt: "Mountains reflected in a lake",
    thumbnail: { class: "aspect-square object-top" },
}} />
```

Use `image.content` when the enlarged view needs its own Astro Image props,
such as different widths or quality. If you use Astro to crop the thumbnail
file itself, set `content: {}` to zoom the original source. Captioned items
render the enlarged view in a dialog.

A local import supplies its dimensions. For a string source, set `width` and
`height` on `image`. For an allowed remote URL, Astro can read the dimensions
with `inferSize: true`.

## Default Grid

The default grid keeps images in source order and gives each row the same
height. At three columns, seven images form rows of three, two, and two.
At two columns, a final image on its own fills the row. The grid chooses the
tile widths automatically.

## Bento Grid

Set `layout="bento"` to make the root a CSS grid. Its default column template
uses `repeat(auto-fill, minmax(...))`. Each item occupies one cell unless you
give it a span. Use `class` on the grid to set your own column template and
`class` on an item to set its row or column span.

```astro
<LightboxGrid layout="bento" class="grid-cols-[repeat(3,minmax(0,1fr))]">
    <LightboxGridItem image={lead} class="col-span-2 row-span-2" />
    {images.map((image) => <LightboxGridItem image={image} />)}
</LightboxGrid>
```

The example below uses the named `span` options.

```astro
---
import future from "@/assets/images/taking-in-the-future.png"
import diagram from "@/assets/wizard/automation-design.png"
import staff from "@/assets/wizard/wizard-in-field-looking-at-planet.png"
import wizard from "@/assets/wizard/wizard-on-moon.jpeg"
import town from "@/assets/wizard/wizard-overlooking-town.png"
import overlook from "@/assets/wizard/wizard-watching-employees.png"
import {
  LightboxGrid,
  LightboxGridItem,
  type LightboxGridItemProps,
} from "@/components/ui/lightbox-grid"

const images = [
  { image: { src: town, alt: "A wizard looking over a town" }, span: "tall" },
  {
    image: { src: future, alt: "A figure taking in a distant future skyline" },
    span: "square",
  },
  {
    image: { src: diagram, alt: "A diagram of an automated workshop" },
    span: "wide",
  },
  { image: { src: staff, alt: "A wizard with a staff" }, span: "square" },
  { image: { src: overlook, alt: "A wizard above a town" }, span: "square" },
  { image: { src: wizard, alt: "A wizard portrait" }, span: "square" },
] satisfies LightboxGridItemProps[]
---

<div class="w-full p-4">
  <LightboxGrid layout="bento" rowHeight="9rem" gap="0.75rem">
    {images.map(({ image, span }) => (
      <LightboxGridItem image={image} span={span} />
    ))}
  </LightboxGrid>
</div>
```

The thumbnail fills its bento cell. Set `image.thumbnail.class` to change the crop position.

## Masonry Grid

Use the reusable [Masonry Grid](/ui/components/masonry-grid) with
`LightboxGridItem`, as this example shows. `LightboxGrid layout="masonry"`
also uses that same component. Each item goes into the shortest column.
`span`, `rowHeight`, and `minRows` have no effect on masonry.

Masonry thumbnails use their natural aspect ratio. This example sets different
thumbnail crops and opens the full source image on zoom.

```astro
---
import storm from "@/assets/images/futuristic-storm.png"
import mountains from "@/assets/images/mountain-beyond-lake-scene.png"
import field from "@/assets/images/open-field-illustration.png"
import waterfall from "@/assets/images/waterfall-field-scene.png"
import planet from "@/assets/wizard/wizard-in-field-looking-at-planet.png"
import {
  type LightboxGridItemProps,
  LightboxGridItem,
} from "@/components/ui/lightbox-grid"
import { MasonryGrid } from "@/components/ui/masonry-grid"

const images = [
  {
    src: mountains,
    alt: "Mountains beyond a lake",
    thumbnail: { class: "aspect-4/5" },
  },
  { src: storm, alt: "A futuristic storm", thumbnail: { class: "aspect-8/5" } },
  {
    src: waterfall,
    alt: "A waterfall in a field",
    thumbnail: { class: "aspect-square" },
  },
  {
    src: planet,
    alt: "A wizard looking at a planet",
    thumbnail: { class: "aspect-8/11" },
  },
  {
    src: field,
    alt: "An open field",
    thumbnail: {
      class:
        "aspect-square @min-[30rem]/masonry:h-[calc(var(--masonry-width)-var(--masonry-gap))]",
    },
  },
] satisfies LightboxGridItemProps["image"][]
---

<div class="mx-auto w-full max-w-2xl p-4">
  <MasonryGrid gap="0.75rem">
    {images.map((image) => (
      <LightboxGridItem image={image} />
    ))}
  </MasonryGrid>
</div>
```

Drag the example's right handle, or focus it and use the arrow keys.

### CSS columns

For a gallery that reads down each column, place the items in a CSS
multi-column container. The browser balances the columns. Each tile keeps
its natural height, and `break-inside-avoid` keeps the tile in one column.

```astro
<div class="columns-1 gap-3 sm:columns-2 lg:columns-3">
    {images.map((image) => (
        <LightboxGridItem image={image} class="mb-3 break-inside-avoid" />
    ))}
</div>
```

## API

`LightboxGrid` accepts native div attributes and these options:

### LightboxGridProps

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

With `minCols={1}`, the regular grid uses one column below 24rem, two from
24rem, and three from 32rem. Bento fits tracks to the available width. Masonry
switches to two columns at 30rem and four at 48rem. Each breakpoint uses the
container width. `minCols` sets a lower limit.

Both counts accept positive integers. Set `minCols={6}` and `minRows={5}` to
reserve five rows and fit six images in a full row. More images
create additional rows. The last row shares its width among the remaining
images. Bento uses the requested number of columns for its tile spans. Masonry
uses the column count and sizes its height from the items.

Set `--lightbox-grid-gap` and `--lightbox-grid-row-height` in
`style` to override the corresponding props. `rowHeight` sizes both explicit
and automatic rows in grid and bento layouts.

### LightboxGridItemProps

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

In bento, `wide` spans two columns, `tall` spans two rows, and `large` spans
both from a container width of 24rem. `auto` and `square` occupy one cell.
Use item classes for other spans or breakpoints. Bento fills empty cells, so
visual order can differ from source order.

The [registry source](/ui/r/lightbox-grid.json) includes both parts.

Items without a caption use `LightboxImage`. Press Enter or Space to zoom in.
Click again or press Escape to close. A captioned item opens a dialog with
the image description as its title. See [Lightbox](/ui/components/lightbox).

## When to use Lightbox Grid

Use LightboxGrid to arrange related images before opening their detail views. Choose the layout and minimum column count from the supported props. Set row height and gap to suit the image proportions.

## Keyboard and behavior

Each image trigger needs a clear name and visible focus. Keep the DOM order meaningful even when the grid has varied spans. The visual layout should not be used to change the reading order of a story.

## Theme and layout

Container queries adapt the grid to its available width. Check it inside narrow cards as well as full-page sections. Supply image dimensions and intentional crops; the grid cannot restore detail removed by a crop.
