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

Lightbox for Astro

Astro image zoom and media previews built on Dialog.

Usage

---
import { Image } from "astro:assets"
import { Lightbox, LightboxContent, LightboxTrigger } from "@/components/ui/lightbox"
import lake from "../assets/lake.jpg"
---

<Lightbox>
  <LightboxTrigger hoverZoom aria-label="Enlarge mountain lake">
    <Image src={lake} alt="Mountains reflected in a lake" />
  </LightboxTrigger>
  <LightboxContent label="Mountain lake" caption="A quiet morning.">
    <Image src={lake} alt="Mountains reflected in a lake" loading="lazy" />
  </LightboxContent>
</Lightbox>

Lightbox is a direct export of Dialog. LightboxTrigger is a thumbnail button. LightboxContent includes the overlay, close button, hidden accessible title, media container, and optional caption.

Set label to name the dialog. It does not replace the image’s alt text. hoverZoom adds a small preview scale on hover and respects reduced motion. Keep links and buttons out of LightboxTrigger; it is already a button.

Captions and media

Use caption for plain text. Use the caption slot for links or other markup. The slot takes precedence over the prop.

<LightboxContent label="Mountain lake">
  <Image src={lake} alt="Mountains reflected in a lake" loading="lazy" />
  <span slot="caption">Photograph by <a href="#photographer">Alex Morgan</a>.</span>
</LightboxContent>

The default slot accepts an image, video, iframe, or custom layout. Put media directly in the slot. mediaClass changes the inner container and its direct child sizing; class changes the dialog panel.

Direct image and video children fit their content within the available width and height. They stay centered, and clicks beside them reach the backdrop in the default variant. Carousels, iframes, and custom layouts keep the full media width.

<LightboxContent
  label="Document preview"
  mediaClass="mx-auto max-w-3xl *:h-[min(70dvh,720px)]"
>
  <iframe src={previewUrl} title="Document preview" class="border-0" />
</LightboxContent>

Give iframes a title and an explicit height or aspect ratio. The lightbox does not stop video or iframe playback when it closes.

Image loading

Use separate thumbnail and enlarged images so each can have suitable dimensions and sizes. Astro can reuse matching image transforms. Keep the enlarged image lazy. Use priority only for a key thumbnail visible on initial page load. See Astro’s image options.

Panel view

The default variant uses a dark backdrop and fills the screen. Set variant="panel" for a centered panel.

API Reference

Installation

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

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

No extra packages are required.

Copy the files

src/components/ui/lightbox/index.ts
// Dialog supplies the root behavior. Lightbox supplies the media layout.
export { default as Lightbox } from '../dialog/dialog.astro'
export { default as LightboxContent } from './lightbox-content.astro'
export { default as LightboxTrigger } from './lightbox-trigger.astro'
export { default as LightboxImage } from './lightbox-image.astro'
export type {
    LightboxContentProps,
    LightboxProps,
    LightboxTriggerProps,
} from './types.ts'
src/components/ui/lightbox/types.ts
import type { DialogOptions } from '../dialog/types.ts'
import type { LightboxPopupVariantProps } from './lightbox-variants.ts'

/** Options for the dialog that shows the enlarged view. */
export type LightboxProps = Omit<DialogOptions, 'alertDialog'>

/** Props for the thumbnail button. */
export interface LightboxTriggerProps {
    /**
     * Scale the preview on hover.
     * Adds the class `hover:scale-105`.
     *
     * @default false
     */
    hoverZoom?: boolean
}

/** Props for the enlarged media view. */
export interface LightboxContentProps {
    /** Accessible name, rendered as a visually hidden dialog title. */
    label: string
    /** Text below the media. The caption slot takes precedence. */
    caption?: string
    /** Classes for the media container. */
    mediaClass?: string
    /**
     * `panel` centers the media in a dialog.
     * `default` fills the screen and uses a dark backdrop.
     *
     * @default 'default'
     */
    variant?: LightboxPopupVariantProps['variant']
    /**
     * Show the close button.
     *
     * @default true
     */
    showCloseButton?: boolean
    /** Extra classes for the backdrop. */
    overlayClass?: string
}
src/components/ui/lightbox/lightbox-image.astro
---
import { Image } from "astro:assets"
import type { ComponentProps } from "astro/types"
import { cn } from "cn"

type Props = ComponentProps<typeof Image>

const {
  widths = [100, 250, 500, 1000, 1250],
  class: className,
  ...props
} = Astro.props
---

<Image
  {...({ ...props, widths } as Props)}
  data-slot="lightbox-image-trigger"
  role="button"
  tabindex={0}
  aria-label={`Enlarge image: ${props.alt}`}
  aria-expanded="false"
  class={cn(
    "cursor-zoom-in focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring",
    className,
  )}
/>

<script>
  // Image-only zoom. Dialog remains the container for captions and carousels.
  const selector = '[data-slot="lightbox-image-trigger"]'
  let active:
    { close: (immediate?: boolean, restoreFocus?: boolean) => void } | undefined

  function open(image: HTMLImageElement) {
    if (!image.complete || !image.naturalWidth) return
    active?.close(true, false)

    const rect = image.getBoundingClientRect()
    if (!rect.width || !rect.height) return

    const overlay = document.createElement("button")
    overlay.type = "button"
    overlay.dataset.slot = "lightbox-overlay"
    overlay.setAttribute("aria-label", "Close enlarged image")
    overlay.className =
      "fixed inset-0 z-[100] m-0 size-full cursor-zoom-out border-0 bg-transparent p-0 text-foreground focus-visible:outline-none"

    // Fade only the backdrop so the image stays opaque throughout the zoom.
    const backdrop = document.createElement("span")
    backdrop.dataset.slot = "lightbox-backdrop"
    backdrop.setAttribute("aria-hidden", "true")
    backdrop.className =
      "pointer-events-none absolute inset-0 bg-background/95 backdrop-blur-sm"

    // Do not copy thumbnail classes, IDs, or responsive layout constraints.
    const zoomed = document.createElement("img")
    zoomed.dataset.slot = "lightbox-image"
    zoomed.alt = image.alt
    zoomed.src = image.currentSrc || image.src
    zoomed.srcset = image.srcset
    zoomed.sizes = "90vw"
    zoomed.draggable = false
    zoomed.className =
      "absolute m-0 max-h-none max-w-none origin-top-left object-contain"

    const ratio = image.naturalWidth / image.naturalHeight
    const width = Math.min(
      window.innerWidth * 0.9,
      window.innerHeight * 0.9 * ratio,
    )
    const height = width / ratio
    const left = (window.innerWidth - width) / 2
    const top = (window.innerHeight - height) / 2
    Object.assign(zoomed.style, {
      width: `${width}px`,
      height: `${height}px`,
      left: `${left}px`,
      top: `${top}px`,
    })
    const thumbnailTransform = () => {
      const bounds = image.getBoundingClientRect()
      return `translate(${bounds.left - left}px, ${bounds.top - top}px) scale(${bounds.width / width}, ${bounds.height / height})`
    }
    const reducedMotion = window.matchMedia(
      "(prefers-reduced-motion: reduce)",
    ).matches
    const timing = {
      duration: reducedMotion ? 0 : 300,
      easing: "cubic-bezier(0.2, 0, 0, 1)",
      fill: "both" as const,
    }
    const visibility = image.style.getPropertyValue("visibility")
    const visibilityPriority = image.style.getPropertyPriority("visibility")
    const events = new AbortController()
    let closing = false
    let removed = false

    overlay.append(backdrop, zoomed)
    document.body.append(overlay)
    image.setAttribute("aria-expanded", "true")
    overlay.focus({ preventScroll: true })
    image.style.setProperty("visibility", "hidden")

    let movement = zoomed.animate(
      [{ transform: thumbnailTransform() }, { transform: "none" }],
      timing,
    )
    let fade = backdrop.animate([{ opacity: 0 }, { opacity: 1 }], timing)

    function remove(restoreFocus: boolean) {
      if (removed) return
      removed = true
      events.abort()
      movement.cancel()
      fade.cancel()
      overlay.remove()
      if (visibility)
        image.style.setProperty("visibility", visibility, visibilityPriority)
      else image.style.removeProperty("visibility")
      image.setAttribute("aria-expanded", "false")
      if (active === instance) active = undefined
      if (restoreFocus && image.isConnected)
        image.focus({ preventScroll: true })
    }

    function close(immediate = false, restoreFocus = true) {
      if (immediate) return remove(restoreFocus)
      if (closing) return
      closing = true
      const transform = getComputedStyle(zoomed).transform
      const opacity = getComputedStyle(backdrop).opacity
      movement.cancel()
      fade.cancel()
      movement = zoomed.animate(
        [{ transform }, { transform: thumbnailTransform() }],
        timing,
      )
      fade = backdrop.animate([{ opacity }, { opacity: 0 }], timing)
      void movement.finished.then(
        () => remove(restoreFocus),
        () => {},
      )
    }

    const instance = { close }
    active = instance
    const { signal } = events
    overlay.addEventListener("click", () => close(), { signal })
    document.addEventListener(
      "keydown",
      (event) => {
        if (event.key === "Escape") {
          event.preventDefault()
          close()
        } else if (event.key === "Tab") {
          // Return to the thumbnail before the browser moves to the next control.
          close(true)
        }
      },
      { signal },
    )
    document.addEventListener(
      "scroll",
      () => {
        // A scroll queued before opening must not close the new zoom.
        const bounds = image.getBoundingClientRect()
        if (bounds.top !== rect.top || bounds.left !== rect.left) close(true)
      },
      {
        capture: true,
        passive: true,
        signal,
      },
    )
    window.addEventListener("resize", () => close(true), { signal })
  }

  // Delegation also covers examples inserted after the first page load.
  document.addEventListener("click", (event) => {
    const image = event.target
    if (image instanceof HTMLImageElement && image.matches(selector))
      open(image)
  })
  document.addEventListener("keydown", (event) => {
    const image = event.target
    if (!(image instanceof HTMLImageElement) || !image.matches(selector)) return
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault()
      if (!event.repeat) open(image)
    }
  })
  document.addEventListener("astro:before-swap", () =>
    active?.close(true, false),
  )
</script>
src/components/ui/lightbox/lightbox-content.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import {
  DialogClose,
  DialogDescription,
  DialogOverlay,
  DialogPortal,
  DialogTitle,
} from "../dialog/index.ts"
import {
  lightboxOverlayVariants,
  lightboxPopupVariants,
} from "./lightbox-variants.ts"
import type { LightboxContentProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & LightboxContentProps

const {
  class: className,
  label,
  caption,
  mediaClass,
  overlayClass,
  showCloseButton = true,
  style: styleProp,
  variant = "default",
  ...props
} = Astro.props

if (!label?.trim()) throw new Error("LightboxContent requires a label.")

const style =
  typeof styleProp === "string"
    ? `z-index: calc(var(--dialog-content-stack-index, 0) * 2 + 101); ${styleProp}`
    : {
        "z-index": "calc(var(--dialog-content-stack-index, 0) * 2 + 101)",
        ...styleProp,
      }
---

<DialogPortal>
  <DialogOverlay
    class={cn(lightboxOverlayVariants({ variant }), overlayClass)}
  />
  <div
    data-slot="dialog-content"
    data-variant={variant}
    hidden
    class={cn(lightboxPopupVariants({ variant }), className)}
    style={style}
    {...props}
  >
    {showCloseButton && (
      <DialogClose
        variant="ghost"
        size="icon-sm"
        class={cn(
          "pointer-events-auto absolute top-4 right-4",
          variant === "default" && "text-white hover:bg-white/12",
        )}
      />
    )}
    <DialogTitle class="sr-only" data-lightbox-title>
      {label}
    </DialogTitle>
    <div
      data-slot="lightbox-media"
      class={cn(
        "size-full *:pointer-events-auto *:mx-auto *:h-auto *:max-h-[calc(100dvh-10rem)] *:w-full *:object-contain [&>:where(img,video)]:w-full [&>:where(img,video)]:max-w-full",
        mediaClass,
      )}
    >
      <slot />
    </div>
    {(caption || Astro.slots.has("caption")) && (
      <DialogDescription
        class={cn(
          "pointer-events-auto shrink-0 text-center",
          variant === "default" && "text-white/80",
        )}
      >
        <slot name="caption">{caption}</slot>
      </DialogDescription>
    )}
  </div>
</DialogPortal>
src/components/ui/lightbox/lightbox-trigger.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import type { LightboxTriggerProps } from "./types.ts"

type Props = Omit<HTMLAttributes<"button">, "type"> & LightboxTriggerProps

const { hoverZoom = false, class: className, ...props } = Astro.props

// The button clips the scale.
// hoverZoom adds hover:scale-105 on the preview.
---

<button
  data-slot="dialog-trigger"
  class={cn(
    "bg-muted grid w-full cursor-zoom-in overflow-hidden rounded-xl border-0 p-0 focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-ring",
    className,
  )}
  {...props}
  type="button"
>
  <span
    data-slot="lightbox-preview"
    class={cn(
      "min-h-0 w-full [&_img]:pointer-events-none [&_img]:block [&_img]:max-w-full",
      hoverZoom &&
        "transition-transform duration-300 hover:scale-105 ease-in-out motion-reduce:transform-none motion-reduce:transition-none",
    )}
  >
    <slot />
  </span>
</button>
src/components/ui/lightbox/lightbox-variants.ts
import { cva, type VariantProps } from 'class-variance-authority'

/**
 * Classes for the enlarged panel.
 * `panel` centers the media. `default` fills the screen.
 */
export const lightboxPopupVariants = cva(
    'data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 duration-100 outline-none motion-reduce:animate-none!',
    {
        defaultVariants: {
            variant: 'default',
        },
        variants: {
            variant: {
                panel: 'bg-popover text-popover-foreground ring-foreground/10 @container/dialog fixed top-1/2 left-1/2 z-50 grid max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-6xl -translate-x-1/2 -translate-y-1/2 gap-3 overflow-y-auto rounded-xl p-4 pt-14 text-sm ring-1 sm:max-w-6xl',
                default:
                    'pointer-events-none fixed inset-0 flex flex-col justify-center gap-4 overflow-visible bg-transparent px-3 py-16 text-white shadow-none ring-0',
            },
        },
    },
)

/**
 * Extra classes for the backdrop.
 * DialogOverlay supplies the base backdrop. These classes replace its color.
 * `panel` keeps that base. `default` uses a dark backdrop.
 */
export const lightboxOverlayVariants = cva('', {
    defaultVariants: {
        variant: 'panel',
    },
    variants: {
        variant: {
            panel: '',
            default: 'bg-black/90',
        },
    },
})

export type LightboxPopupVariantProps = VariantProps<
    typeof lightboxPopupVariants
>
export type LightboxOverlayVariantProps = VariantProps<
    typeof lightboxOverlayVariants
>

Simple image zoom

Use LightboxImage for a single image that expands from its position on the page. It uses a small browser script and has no Dialog container. It accepts Astro Image props, including src, alt, widths, and sizes.

Click the image, or use Enter or Space, to open it. Click again or press Escape to close it. Scrolling, resizing, and page changes also close the zoom. The animation respects reduced motion. Use the Dialog parts above for captions and other media, or Lightbox Carousel for a gallery.

Custom composition

Use standard Dialog parts for custom titles, controls, and panels. LightboxContent supplies its own title and caption; do not add a second DialogTitle or DialogDescription inside it. Set showCloseButton={false} only when the content includes another close control.

Lightbox Carousel adds navigation between items. Lightbox Grid arranges independent lightboxes.

API reference

Source: Lightbox registry item.

LightboxProps

Root options are inherited from Dialog.

PropType
defaultOpen?boolean

Initial open state

Typeboolean
closeOnClickOutside?boolean

Close when clicking overlay

Typeboolean
closeOnEscape?boolean

Close when pressing Escape

Typeboolean
lockScroll?boolean

Lock body scroll when open

Typeboolean

LightboxContentProps

PropType
labelstring

Accessible name, rendered as a visually hidden dialog title.

Typestring
caption?string

Text below the media. The caption slot takes precedence.

Typestring
mediaClass?string

Classes for the media container.

Typestring
variant?LightboxPopupVariantProps['variant']

`panel` centers the media in a dialog. `default` fills the screen and uses a dark backdrop.

TypeLightboxPopupVariantProps['variant']
Default'default'
showCloseButton?boolean

Show the close button.

Typeboolean
Defaulttrue
overlayClass?string

Extra classes for the backdrop.

Typestring

LightboxTriggerProps

PropType
hoverZoom?boolean

Scale the preview on hover. Adds the class `hover:scale-105`.

Typeboolean
Defaultfalse

Migration

Replace LightboxTitle with the label prop. Put media directly inside LightboxContent and move any LightboxMedia classes to mediaClass. Replace LightboxDescription with caption or the caption slot. Rename variant="viewport" to variant="default" or omit it. For custom panels, import DialogPortal, DialogOverlay, and DialogClose from Dialog.

Keyboard and layout

Dialog manages focus, Escape, outside clicks, and scroll locking. A close control must remain available. Check tall media and long captions on a phone.