Lightbox Carousel for Astro
A carousel with items that when clicked, open the carousel in a lightbox dialog, allowing for a larger view with the same carousel layout.
Installation
bunx --bun shadcn@latest add @gnostic/lightbox-carouselnpx shadcn@latest add @gnostic/lightbox-carouselpnpm dlx shadcn@latest add @gnostic/lightbox-carouselComplete the Installation guide first. Then copy the component files below.
Install component packages
bun add @data-slot/core @data-slot/dialogCopy the files
src/components/ui/lightbox-carousel/index.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
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import CarouselItem from "../carousel/carousel-item.astro"
import CarouselLayer from "../carousel/carousel-layer.astro"
import { LightboxTrigger } from "../lightbox/index.ts"
import type { LightboxCarouselItemProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & LightboxCarouselItemProps
const {
alt,
caption,
class: className,
hoverZoom = true,
...props
} = Astro.props
if (!alt) {
throw new Error("LightboxCarouselItem requires alt.")
}
if (!Astro.slots.has("preview") || !Astro.slots.has("content")) {
throw new Error("LightboxCarouselItem needs preview and content slots.")
}
// The content slot stays in a template until the root moves it into the
// enlarged carousel. The preview slot stays in the page carousel.
---
<CarouselItem
data-lightbox-carousel-item
data-lightbox-alt={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: ${alt}`}
>
<slot name="preview" />
</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" />
</div>
</CarouselItem>
</template>
</CarouselItem>
src/components/ui/lightbox-carousel/lightbox-carousel.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import {
Carousel,
CarouselContent,
CarouselNext,
CarouselPrevious,
} from "../carousel/index.ts"
import { Lightbox, LightboxContent } from "../lightbox/index.ts"
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
import type { CarouselOptions } from '../carousel/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 {
/** Accessible name for the slide button and the enlarged dialog title. */
alt: string
/** 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
import {
clearRootBinding,
getRootBinding,
getRoots,
hasRootBinding,
setRootBinding,
} from '@data-slot/core'
import { createDialog, type DialogController } from '@data-slot/dialog'
import {
createCarousel,
type CarouselController,
} from '../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
}
Usage
Use LightboxCarousel and LightboxCarouselItem with the normal Carousel
content and controls. Each item needs a preview slot for the page and a
content slot for the enlarged view.
---
import { Image } from "astro:assets"
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 alt="Mountains reflected in a lake" caption="A quiet morning.">
<Image slot="preview" src={lake} alt="" class="aspect-3/2 w-full object-cover" />
<Image slot="content" src={lake} alt="Mountains reflected in a lake" loading="lazy" />
</LightboxCarouselItem>
</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. Keep links and buttons out of preview; it is inside a button.
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 also apply
here. This example scrolls two page items
at a time and applies a small scale effect.
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 preview slot. Allow space for an arc through
CarouselContent’s viewportClass prop. See Carousel effects.
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.
LightboxCarouselProps
label?string
Accessible name for the page carousel.
string'Image gallery'carouselOptions?CarouselEmblaOptions
JSON-compatible Embla options. Orientation and Astro parts control the axis and elements.
CarouselEmblaOptionsorientation?'horizontal' | 'vertical'
Scroll axis for the carousel.
'horizontal' | 'vertical'"horizontal"effects?CarouselEffects
Independent effects applied to the optional inner parts.
CarouselEffectsThe root also accepts the shared Carousel options:
carouselOptions?CarouselEmblaOptions
JSON-compatible Embla options. Orientation and Astro parts control the axis and elements.
CarouselEmblaOptionsorientation?'horizontal' | 'vertical'
Scroll axis for the carousel.
'horizontal' | 'vertical'"horizontal"effects?CarouselEffects
Independent effects applied to the optional inner parts.
CarouselEffectsLightboxCarouselItemProps
altstring
Accessible name for the slide button and the enlarged dialog title.
stringcaption?string
Optional text under the enlarged image.
stringhoverZoom?boolean
Scale the slide preview on hover. The preview uses `hover:scale-105`.
booleantrueBoth named slots are required. Each item also accepts native div attributes.
Client control
The component initializes itself. Use the controller to open an item from a client script:
<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.
Keep loading="lazy" on enlarged images, as in the usage example. Astro’s
Image uses this value 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
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.





