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

Lightbox Grid for Astro

Responsive Astro gallery grids with normal grid, bento, and masonry layouts.

Installation

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

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

No extra packages are required.

Copy the files

src/components/ui/lightbox-grid/index.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
export interface LightboxGridProps {
    /**
     * Equal grid cells, mixed bento spans, or natural-height masonry items.
     * @default 'bento'
     */
    layout?: 'grid' | 'bento' | 'masonry'
    /**
     * The minimum number of columns the grid should have
     *
     * @default 1
     */
    minCols?: 1 | 2 | 3 | 4
    /**
     * The minimum number of rows the grid should have
     *
     * @default 1
     */
    minRows?: 1 | 2 | 3 | 4
    /**
     * 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
}

export interface LightboxGridItemProps {
    /** Accessible trigger label and dialog title. */
    alt: string
    caption?: string
    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
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { MasonryGrid } from "../masonry-grid/index.ts"
import type { LightboxGridProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & LightboxGridProps

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

const columns = {
  1: "grid-cols-1 @min-[24rem]/lightbox-grid:grid-cols-2 @min-[48rem]/lightbox-grid:grid-cols-4",
  2: "grid-cols-2 @min-[48rem]/lightbox-grid:grid-cols-4",
  3: "grid-cols-3 @min-[48rem]/lightbox-grid:grid-cols-4",
  4: "grid-cols-4",
}
const variables = {
  "--lightbox-grid-row-height": rowHeight,
  "--lightbox-grid-gap": gap,
}
// Preserve CSS values that contain colons or semicolons.
const mergedStyle =
  typeof style === "string"
    ? `--lightbox-grid-row-height:${rowHeight};--lightbox-grid-gap:${gap};${style}`
    : { ...variables, ...style }
---

<div
  data-slot="lightbox-grid"
  data-lightbox-layout={layout}
  class={cn("@container/lightbox-grid", className)}
  style={mergedStyle}
  {...props}
>
  {layout === "masonry" ? (
    <MasonryGrid minCols={minCols} gap="var(--lightbox-grid-gap)">
      <slot />
    </MasonryGrid>
  ) : (
    <div
      class={cn(
        "grid auto-rows-(--lightbox-grid-row-height) gap-(--lightbox-grid-gap)",
        layout === "bento" && "grid-flow-dense",
        columns[minCols],
      )}
      style={`grid-template-rows:repeat(${minRows},var(--lightbox-grid-row-height))`}
    >
      <slot />
    </div>
  )}
</div>
src/components/ui/lightbox-grid/lightbox-grid-item.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import {
  Lightbox,
  LightboxContent,
  LightboxTrigger,
} from "../lightbox/index.ts"
import type { LightboxGridItemProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & LightboxGridItemProps

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

if (!Astro.slots.has("thumbnail") || !Astro.slots.has("content")) {
  throw new Error("LightboxGridItem needs thumbnail and content slots.")
}
---

<Lightbox
  class={cn(
    "min-h-0 min-w-0",
    "in-data-[lightbox-layout=bento]:@min-[24rem]/lightbox-grid:data-[lightbox-span=wide]:col-span-2 in-data-[lightbox-layout=bento]:@min-[24rem]/lightbox-grid:data-[lightbox-span=large]:col-span-2 in-data-[lightbox-layout=bento]:@min-[24rem]/lightbox-grid:data-[lightbox-span=tall]:row-span-2 in-data-[lightbox-layout=bento]:@min-[24rem]/lightbox-grid:data-[lightbox-span=large]:row-span-2",
    "in-data-[lightbox-layout=bento]:@min-[24rem]/lightbox-grid:data-[lightbox-span=auto]:[&:nth-child(6n+1_of_[data-lightbox-span])]:row-span-2 in-data-[lightbox-layout=bento]:@min-[24rem]/lightbox-grid:data-[lightbox-span=auto]:[&:nth-child(6n+4_of_[data-lightbox-span])]:col-span-2",
    className,
  )}
  data-lightbox-span={span}
  {...props}
>
  <LightboxTrigger
    hoverZoom={hoverZoom}
    class="w-full in-data-[lightbox-layout=bento]:h-full in-data-[lightbox-layout=grid]:h-full"
    aria-label={`View image: ${alt}`}
  >
    <slot name="thumbnail" />
  </LightboxTrigger>
  <LightboxContent label={alt} caption={caption}>
    <slot name="content" />
  </LightboxContent>
</Lightbox>

Usage

Map images in the consumer. Supply both named slots for each item. You control image dimensions, crop, loading, and Astro image optimization.

---
import { Image } from "astro:assets"
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 layout="grid">
  {images.map((image) => (
    <LightboxGridItem alt={image.alt}>
      <Image
        slot="thumbnail"
        {...image}
        widths={[320, 640, 960]}
        sizes="auto, 100vw"
        class="size-full object-cover"
        loading="lazy"
      />
      <Image
        slot="content"
        {...image}
        widths={[640, 1200, 1920]}
        sizes="(min-width: 72rem) 70rem, calc(100vw - 4rem)"
        loading="lazy"
      />
    </LightboxGridItem>
  ))}
</LightboxGrid>

The grid accepts children only. It does not accept an images array or render images internally. Keep links and buttons out of the thumbnail slot because it is inside a button. alt supplies the trigger label and dialog title; set image alt text on your images too.

One source, two views

Both slots use the same imported image. Astro generates srcset from widths. The thumbnail uses smaller candidates; the dialog uses larger candidates. Choose widths that suit your source images and display sizes.

For lazy thumbnails, sizes="auto, 100vw" lets supporting browsers use the rendered tile width, including changes to its container. 100vw is the fallback. The dialog’s sizes matches its maximum width and padding. Adjust these values if you change the layout. The browser selects a candidate for each view; a small thumbnail does not mean the dialog must use that same file.

Normal grid

Use layout="grid" for equal cells. The first example uses this option. Item spans have no effect in this layout.

Bento spans

Use layout="bento" for mixed tile sizes. The example has a tall tile, single cells, and tiles that span two columns. Spans start at a container width of 24rem. Smaller containers use a single column.

Use Image, Picture, or your own markup in thumbnail and content. For bento tiles, size-full object-cover fills the tile.

Masonry and resizing

Use the reusable 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.

Use h-auto w-full on thumbnails. Supply different image dimensions to show items with different heights. This example uses different thumbnail crops and keeps the full source image in each dialog.

Drag the example’s right handle, or focus it and use the arrow keys. The docs wrapper adds the handle with <Component viewport={false} resizable />. The handle is not part of the example source.

API

LightboxGrid accepts native div attributes and these options:

LightboxGridProps

PropType
layout?'grid' | 'bento' | 'masonry'

Equal grid cells, mixed bento spans, or natural-height masonry items.

Type'grid' | 'bento' | 'masonry'
Default'bento'
minCols?1 | 2 | 3 | 4

The minimum number of columns the grid should have

Type1 | 2 | 3 | 4
Default1
minRows?1 | 2 | 3 | 4

The minimum number of rows the grid should have

Type1 | 2 | 3 | 4
Default1
rowHeight?string

The height of each row in the grid as a CSS value

Typestring
Default'14rem' // 224px
gap?string

A valid CSS gap value

Typestring
Default'0.5rem'

Grid and bento use one column below 24rem, two from 24rem, and four from 48rem. Masonry uses 30rem for the two-column breakpoint. minCols sets a lower limit. 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.

LightboxGridItem accepts native div attributes and these options:

LightboxGridItemProps

PropType
altstring

Accessible trigger label and dialog title.

Typestring
caption?string
Typestring
span?'auto' | 'square' | 'wide' | 'tall' | 'large'
Type'auto' | 'square' | 'wide' | 'tall' | 'large'
hoverZoom?boolean

Scale the thumbnail on hover. The preview uses `hover:scale-105`.

Typeboolean
Defaulttrue

Both thumbnail and content slots are required. In bento, wide spans two columns, tall spans two rows, and large spans both. auto repeats a pattern with a tall first tile and a wide fourth tile. square occupies one cell; its shape follows the column width and row height. Bento fills empty cells, so visual order can differ from source order. Use layout="grid" when strict row order matters.

The registry source includes both parts.

Pass local image imports directly to Astro Image. String sources need width and height. Remote optimization also needs an allowed domain or remote pattern in Astro configuration. See the Astro image guide.

The enlarged view is a Lightbox. Dialog handles focus, Escape, outside clicks, and scroll locking. Close the dialog to select another image.

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.