---
title: Lightbox Carousel for Astro
description: "A carousel with items that when clicked, open the carousel in a lightbox dialog, allowing for a larger view with the same carousel layout."
sidebar:
    label: "Lightbox Carousel"
    badge: new
seo:
    title: "Lightbox Carousel for Astro | Shadcn & Tailwind CSS"
related:
    - /components/carousel
    - /components/lightbox
    - /components/lightbox-grid
---

```astro
---
import {
  CarouselContent,
  CarouselPrevious,
  CarouselNext,
} from "@/components/ui/carousel"
import {
  LightboxCarousel,
  LightboxCarouselItem,
} from "@/components/ui/lightbox-carousel"

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",
  },
  {
    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="mx-auto w-full max-w-3xl px-14 py-4">
  <LightboxCarousel>
    <CarouselContent>
      {images.map((image) => (
        <LightboxCarouselItem image={image} />
      ))}
    </CarouselContent>
    <CarouselPrevious />
    <CarouselNext />
  </LightboxCarousel>
</div>
```

## Installation

### Command

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

### Manual

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

Install the component packages:

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

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

```ts
// Page carousel that opens the selected slide in a larger dialog carousel.
export { default as LightboxCarousel } from './lightbox-carousel.astro'
export { default as LightboxCarouselItem } from './lightbox-carousel-item.astro'
export type {
    LightboxCarouselItemProps,
    LightboxCarouselProps,
} from './types.ts'
export { create, createLightboxCarousel } from './lightbox-carousel.ts'
export type { LightboxCarouselController } from './lightbox-carousel.ts'
```

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

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

import CarouselItem from "@/components/ui/carousel/carousel-item.astro"
import CarouselLayer from "@/components/ui/carousel/carousel-layer.astro"
import { LightboxTrigger } from "@/components/ui/lightbox"
import { getLightboxImages } from "@/components/ui/lightbox/lightbox-item-images.ts"

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

type Props = HTMLAttributes<"div"> & LightboxCarouselItemProps

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

const { preview, enlarged } = getLightboxImages(image, "dialog")
---

<CarouselItem
  data-lightbox-carousel-item
  data-lightbox-alt={image.alt}
  data-lightbox-caption={caption}
  class={cn(className)}
  {...props}
>
  <CarouselLayer>
    <LightboxTrigger
      hoverZoom={hoverZoom}
      data-lightbox-open
      aria-haspopup="dialog"
      aria-expanded="false"
      aria-label={`View larger image: ${image.alt}`}
    >
      <slot name="preview">
        <Image
          {...preview}
          class={cn(
            "block aspect-3/2 h-auto w-full object-cover",
            preview.class,
          )}
        />
      </slot>
    </LightboxTrigger>
  </CarouselLayer>
  <template data-lightbox-slide>
    <CarouselItem class="pl-0">
      <div class="*:mx-auto *:block *:h-auto *:max-h-[calc(100dvh-10rem)] *:w-full *:rounded-lg *:object-contain">
        <slot name="content">
          <Image {...enlarged} />
        </slot>
      </div>
    </CarouselItem>
  </template>
</CarouselItem>
```

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

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import {
  Carousel,
  CarouselContent,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
import { Lightbox, LightboxContent } from "@/components/ui/lightbox"
import type { LightboxCarouselProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & LightboxCarouselProps

const {
  label = "Image gallery",
  class: className,
  carouselOptions,
  orientation,
  effects,
  ...props
} = Astro.props
---

<div data-slot="lightbox-carousel" class={cn("w-full", className)} {...props}>
  <Carousel
    carouselOptions={carouselOptions}
    orientation={orientation}
    effects={effects}
    aria-label={label}
    data-lightbox-carousel="inline"
    class="w-full"
  >
    <slot />
  </Carousel>
  <Lightbox>
    <LightboxContent label={label} mediaClass="*:max-h-none">
      <template data-lightbox-carousel-template>
        <Carousel
          carouselOptions={{
            loop: carouselOptions?.loop ?? true,
            direction: carouselOptions?.direction,
          }}
          aria-label={`${label} enlarged`}
          data-lightbox-carousel="expanded"
          class="pointer-events-auto grid w-full grid-cols-[2.75rem_minmax(0,1fr)_2.75rem] items-center gap-x-2 md:gap-x-3 *:data-[slot=carousel-content]:col-start-2 *:data-[slot=carousel-content]:row-start-1 *:data-[slot=carousel-content]:min-w-0"
        >
          <CarouselContent gap="0" viewportClass="relative" />
          <CarouselPrevious
            variant="ghost"
            size="icon-lg"
            class="static! col-start-1 row-start-1 translate-y-0! rounded-full text-white hover:bg-white/12"
          />
          <CarouselNext
            variant="ghost"
            size="icon-lg"
            class="static! col-start-3 row-start-1 translate-y-0! rounded-full text-white hover:bg-white/12"
          />
        </Carousel>
      </template>
      <span slot="caption" data-lightbox-status aria-live="polite" />
    </LightboxContent>
  </Lightbox>
</div>

<script>
  import {
    create,
    type LightboxCarouselController,
  } from "./lightbox-carousel.ts"

  const controllers = new Set<LightboxCarouselController>()
  const clearDisconnected = () => {
    for (const controller of controllers) {
      if (!controller.root.isConnected) {
        controller.destroy()
        controllers.delete(controller)
      }
    }
  }
  const observer = new MutationObserver(clearDisconnected)
  const initialize = () => {
    clearDisconnected()
    for (const controller of create()) controllers.add(controller)
    observer.observe(document.documentElement, {
      childList: true,
      subtree: true,
    })
  }
  const clear = () => {
    observer.disconnect()
    for (const controller of controllers) controller.destroy()
    controllers.clear()
  }

  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", clear)
</script>
```

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

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

/** Page carousel options. The enlarged view shows one item per snap. */
export interface LightboxCarouselProps extends CarouselOptions {
    /**
     * Accessible name for the page carousel.
     *
     * @default 'Image gallery'
     */
    label?: string
}

/** Props for a thumbnail and its enlarged content. */
export interface LightboxCarouselItemProps {
    /** Image source and alt text, with optional props for the thumbnail and enlarged view. */
    image: LightboxItemImage
    /** Optional text under the enlarged image. */
    caption?: string
    /**
     * Scale the slide preview on hover.
     * The preview uses `hover:scale-105`.
     *
     * @default true
     */
    hoverZoom?: boolean
}
```

#### src/components/ui/lightbox-carousel/lightbox-carousel.ts

```ts
import {
    clearRootBinding,
    getRootBinding,
    getRoots,
    hasRootBinding,
    setRootBinding,
} from '@data-slot/core'
import { createDialog, type DialogController } from '@data-slot/dialog'

import {
    createCarousel,
    type CarouselController,
} from '@/components/ui/carousel/carousel.ts'

const ROOT_SLOT = 'lightbox-carousel'

/** One page carousel and its enlarged dialog view. */
export interface LightboxCarouselController {
    readonly root: HTMLElement
    /** Open an item by its slide index, not its page scroll-snap index. */
    open(index?: number): void
    close(): void
    destroy(): void
}

/** Bind unbound galleries in the scope. */
export function create(
    scope: ParentNode = document,
): LightboxCarouselController[] {
    return getRoots<HTMLElement>(scope, ROOT_SLOT)
        .filter((root) => !hasRootBinding(root, ROOT_SLOT))
        .map((root) => createLightboxCarousel(root))
}

/** Bind one gallery. Repeated calls return the existing controller. */
export function createLightboxCarousel(
    root: HTMLElement,
): LightboxCarouselController {
    const existing = getRootBinding<LightboxCarouselController>(root, ROOT_SLOT)
    if (existing) return existing
    const part = <T extends HTMLElement>(selector: string) =>
        Array.from(root.querySelectorAll<T>(selector)).find(
            (node) => node.closest('[data-slot="lightbox-carousel"]') === root,
        )
    const inline = part<HTMLElement>('[data-lightbox-carousel="inline"]')
    const dialogRoot = part<HTMLElement>('[data-slot="dialog"]')
    const content = part<HTMLElement>('[data-slot="dialog-content"]')
    const template = part<HTMLTemplateElement>(
        'template[data-lightbox-carousel-template]',
    )
    const expandedRoot = template?.content.querySelector<HTMLElement>(
        '[data-lightbox-carousel="expanded"]',
    )
    const track = expandedRoot?.querySelector<HTMLElement>(
        '[data-slot="carousel-viewport"]',
    )
    if (
        !inline ||
        !dialogRoot ||
        !content ||
        !template ||
        !expandedRoot ||
        !track
    ) {
        throw new Error(
            'LightboxCarousel requires an inline carousel and an enlarged carousel template.',
        )
    }

    const page = createCarousel(inline)
    const items = page.api.slideNodes()
    const slides = items.map((item) => {
        const source = item.querySelector<HTMLTemplateElement>(
            'template[data-lightbox-slide]',
        )
        const slide = source?.content.firstElementChild
        if (!source || !(slide instanceof HTMLElement)) {
            throw new Error(
                'LightboxCarousel requires LightboxCarouselItem for each slide.',
            )
        }
        return { source, slide }
    })
    const dialog =
        getRootBinding<DialogController>(dialogRoot, '@data-slot/dialog') ??
        createDialog(dialogRoot)
    const title = content.querySelector('[data-lightbox-title]')
    const status = content.querySelector('[data-lightbox-status]')
    const buttons = items.map((item) =>
        item.querySelector<HTMLButtonElement>('[data-lightbox-open]'),
    )
    for (const button of buttons)
        button?.setAttribute('aria-controls', content.id)
    let expanded: CarouselController | undefined
    let selected = 0
    let placing = false
    let destroyed = false

    const writeStatus = () => {
        const item = items[selected]
        if (!item) return
        if (title) title.textContent = item.dataset.lightboxAlt ?? ''
        const position = `Image ${selected + 1} of ${items.length}`
        const caption = item.dataset.lightboxCaption
        if (status)
            status.textContent = caption ? `${position}. ${caption}` : position
    }
    const onSelect = () => {
        if (placing || !expanded || !dialog.isOpen) return
        selected =
            expanded.api.internalEngine().slideRegistry[
                expanded.api.selectedScrollSnap()
            ]?.[0] ?? selected
        writeStatus()
    }
    const reveal = () => {
        placing = true
        try {
            if (!expanded) {
                for (const { slide } of slides) track.append(slide)
                template.after(expandedRoot)
                for (const button of expandedRoot.querySelectorAll<HTMLElement>(
                    '[data-slot="carousel-previous"], [data-slot="carousel-next"]',
                )) {
                    button.hidden = items.length < 2
                }
                expanded = createCarousel(expandedRoot, {
                    carouselOptions: {
                        direction: page.api.internalEngine().options.direction,
                    },
                    keyboardTarget: content,
                })
                expanded.api.on('select', onSelect)
            } else {
                // A hidden dialog can resize to zero. Measure once after it opens.
                expanded.api.reInit({
                    direction: page.api.internalEngine().options.direction,
                })
            }
            expanded.api.scrollTo(selected, true)
            writeStatus()
        } finally {
            placing = false
        }
    }
    const onChange = (event: Event) => {
        if (event.target !== dialogRoot || !(event instanceof CustomEvent))
            return
        if (event.detail?.open) {
            buttons[selected]?.setAttribute('aria-expanded', 'true')
            reveal()
        } else {
            for (const button of buttons)
                button?.setAttribute('aria-expanded', 'false')
            const snap = page.api
                .internalEngine()
                .slideRegistry.findIndex((group) => group.includes(selected))
            if (snap >= 0) page.api.scrollTo(snap, true)
        }
    }
    const onClick = (event: MouseEvent) => {
        // Embla suppresses clicks after a drag, before this listener runs.
        if (event.defaultPrevented || !(event.target instanceof Element)) return
        const button = event.target.closest<HTMLButtonElement>(
            '[data-lightbox-open]',
        )
        const index = button ? buttons.indexOf(button) : -1
        if (index >= 0) controller.open(index)
    }
    const controller: LightboxCarouselController = {
        root,
        open(index = 0) {
            if (
                destroyed ||
                !Number.isInteger(index) ||
                index < 0 ||
                index >= items.length
            )
                return
            selected = index
            writeStatus()
            // Also restores focus for browsers that do not focus a clicked button.
            if (!dialog.isOpen) buttons[index]?.focus({ preventScroll: true })
            if (dialog.isOpen) reveal()
            else dialog.open()
        },
        close() {
            if (!destroyed) dialog.close()
        },
        destroy() {
            if (destroyed) return
            destroyed = true
            inline.removeEventListener('click', onClick)
            dialogRoot.removeEventListener('dialog:change', onChange)
            expanded?.api.off('select', onSelect)
            expanded?.destroy()
            dialog.destroy()
            page.destroy()
            for (const { source, slide } of slides) source.content.append(slide)
            template.content.append(expandedRoot)
            for (const button of buttons) {
                button?.setAttribute('aria-expanded', 'false')
                button?.removeAttribute('aria-controls')
            }
            clearRootBinding(root, ROOT_SLOT, controller)
        },
    }
    inline.addEventListener('click', onClick)
    dialogRoot.addEventListener('dialog:change', onChange)
    setRootBinding(root, ROOT_SLOT, controller)
    return controller
}
```

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

Use `LightboxCarousel` and `LightboxCarouselItem` with the normal Carousel
content and controls. Pass one `image` with `src` and `alt` to each item.
The thumbnail uses a 3:2 CSS crop. The dialog shows the full image.

```astro
---
import { CarouselContent, CarouselNext, CarouselPrevious } from "@/components/ui/carousel"
import { LightboxCarousel, LightboxCarouselItem } from "@/components/ui/lightbox-carousel"
import lake from "../assets/lake.jpg"
---

<LightboxCarousel label="Landscape gallery">
  <CarouselContent>
    <LightboxCarouselItem
      image={{ src: lake, alt: "Mountains reflected in a lake" }}
      caption="A quiet morning."
    />
  </CarouselContent>
  <CarouselPrevious />
  <CarouselNext />
</LightboxCarousel>
```

A click opens the selected item. Previous and Next in the dialog move one item
at a time. Closing the dialog selects the page scroll group that contains the
viewed item. Set `image.thumbnail` or `image.content` to pass Astro Image props
to one view. For example, `thumbnail: { class: "aspect-square" }` gives the
preview a square crop. A local import supplies its dimensions. For a URL, set
`width` and `height` on `image`, or use `inferSize: true` for an allowed remote host.

## Several slides and effects

Set each item's basis to show several slides. Use `carouselOptions` for Embla
options that can pass through JSON and `effects` for the page effects. The
[Carousel option limits](/ui/components/carousel#embla-options-in-astro) also apply
here. This example scrolls two page items
at a time and applies a small scale effect.

```astro
---
import {
  CarouselContent,
  CarouselPrevious,
  CarouselNext,
} from "@/components/ui/carousel"
import {
  LightboxCarousel,
  LightboxCarouselItem,
} from "@/components/ui/lightbox-carousel"

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",
    caption: "Morning light between the trees.",
  },
  {
    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",
    caption: "The ridge stays above the cloud line.",
  },
  {
    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",
    caption: "The valley holds the last light.",
  },
]
---

<div class="mx-auto w-full max-w-3xl px-14 py-4">
  <LightboxCarousel
    label="Landscape gallery"
    carouselOptions={{ slidesToScroll: 2 }}
    effects={{ scale: { min: 0.94 } }}
  >
    <CarouselContent class="-ml-4">
      {images.map(({ caption, ...image }, i) => (
        <LightboxCarouselItem
          image={{
            ...image,
            thumbnail: { loading: i === 0 ? "eager" : "lazy" },
          }}
          caption={caption}
          class="basis-1/2 pl-4 @min-xl/carousel:basis-1/3"
        />
      ))}
    </CarouselContent>
    <CarouselPrevious />
    <CarouselNext />
  </LightboxCarousel>
</div>
```

Each `LightboxCarouselItem` includes a `CarouselLayer` around its trigger, so
arc, scale, and fade effects work without an extra layer. For inner parallax,
put `CarouselParallax` inside the optional `preview` slot. Allow space for an arc through
`CarouselContent`'s `viewportClass` prop. See [Carousel effects](/ui/components/carousel).

The enlarged view is horizontal and uses one item per snap. It inherits the
page's loop setting and current direction. Page grouping, orientation, and
effects do not change its media layout.

Use `gap` on `CarouselContent` for spacing. `CarouselDots` and the standard
previous and next controls also work in the page carousel.

## API reference

Source: [Lightbox Carousel registry item](/ui/r/lightbox-carousel.json).

### LightboxCarouselProps

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

The root also accepts the shared Carousel options:

<AutoTypeTable
    path="../../packages/ui/src/components/ui/carousel/types.ts"
    name="CarouselOptions"
/>

### LightboxCarouselItem slots

| Prop | Type | Default | Description |
| - | - | - | - |
| `preview?` | `Astro content` | - | Renders inside the slide button that opens the lightbox. |
| `content?` | `Astro content` | - | Renders in the lightbox when the reader opens the slide. |

### LightboxCarouselItemProps

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

Each item accepts native div attributes. Use the optional slots for custom markup.
The image prop supplies both views by default and names the slide button and dialog.

## Client control

The component initializes itself. Use the controller to open an item from a
client script:

```astro
<script>
  import { createLightboxCarousel } from "@/components/ui/lightbox-carousel/lightbox-carousel.ts"

  const root = document.querySelector<HTMLElement>("#landscapes")
  if (root) {
    const gallery = createLightboxCarousel(root)
    // Item indexes start at zero. This opens the third image.
    gallery.open(2)
    // gallery.close()
  }
</script>
```

Set `id="landscapes"` on the root for this example. Repeated setup calls return
the same controller. `create(scope)` binds unbound galleries in that scope.
Call `destroy()` before removing a gallery that your script initializes.
Automatic setup cleans up on Astro navigation and when a root is removed.

The enlarged carousel and its media stay in templates until the first open.
The carousel then remains available for later opens. No global window flag is
used.

Enlarged images use lazy loading by default. Once the dialog opens, the browser can load
nearby slides in advance. This is not a guarantee that only the selected image
downloads. Use smaller images for previews and set `sizes` to match their
display width.

## Migration

Move the slide’s source and alt text to `image`. Move thumbnail options to
`image.thumbnail` and enlarged image options to `image.content`. Remove the
two image slots when the item can render both images.

Rename `opts` to `carouselOptions`. Replace `LightboxCarouselContent`,
`LightboxCarouselPrevious`, and `LightboxCarouselNext` with the matching exports
from Carousel. Remove old zero-gap overrides if you want the normal Carousel
spacing; use `gap="0"` for a flush track.

## Keyboard and behavior

Arrow keys move the open carousel, including when the close button has focus.
Direction follows RTL settings. Editable fields keep their own arrow keys.
Reduced motion disables animated keyboard and button movement. Escape, the
close button, and an overlay click close the dialog. Focus returns to the
thumbnail that opened it. Dragging a thumbnail does not open the dialog.

Use suitable thumbnail and full-size sources to limit image transfer size.
Test captions, controls, and tall images at narrow widths.
