---
title: Carousel for Astro
description: "Embla carousel parts for Astro image and content sequences."
seo:
    title: Carousel for Astro | Shadcn & Tailwind CSS
related:
    - /components/lightbox-carousel
    - /components/lightbox-grid
sidebar:
    label: "Carousel"
---

```astro
---
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
---

<Carousel class="w-full max-w-xl @max-sm:max-w-[calc(100%-2.5rem)]">
  <CarouselContent>
    <CarouselItem class="@min-sm/carousel:basis-1/2 @min-xl/carousel:basis-1/3">
      <div class="bg-muted flex aspect-square items-center justify-center rounded-md">
        <span class="text-3xl font-semibold">1</span>
      </div>
    </CarouselItem>
    <CarouselItem class="@min-sm/carousel:basis-1/2 @min-xl/carousel:basis-1/3">
      <div class="bg-muted flex aspect-square items-center justify-center rounded-md">
        <span class="text-3xl font-semibold">2</span>
      </div>
    </CarouselItem>
    <CarouselItem class="@min-sm/carousel:basis-1/2 @min-xl/carousel:basis-1/3">
      <div class="bg-muted flex aspect-square items-center justify-center rounded-md">
        <span class="text-3xl font-semibold">3</span>
      </div>
    </CarouselItem>
    <CarouselItem class="@min-sm/carousel:basis-1/2 @min-xl/carousel:basis-1/3">
      <div class="bg-muted flex aspect-square items-center justify-center rounded-md">
        <span class="text-3xl font-semibold">4</span>
      </div>
    </CarouselItem>
    <CarouselItem class="@min-sm/carousel:basis-1/2 @min-xl/carousel:basis-1/3">
      <div class="bg-muted flex aspect-square items-center justify-center rounded-md">
        <span class="text-3xl font-semibold">5</span>
      </div>
    </CarouselItem>
  </CarouselContent>
  <CarouselPrevious />
  <CarouselNext />
</Carousel>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/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 embla-carousel
```

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

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

import { cn } from "cn"

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

type Props = HTMLAttributes<"div"> & CarouselContentProps

const {
  class: className,
  style: styleProp,
  gap = "1rem",
  viewportClass,
  ...props
} = Astro.props

const style =
  typeof styleProp === "string"
    ? `--carousel-gap: ${gap}; ${styleProp}`
    : {
        "--carousel-gap": gap,
        ...styleProp,
      }
---

<div class={cn("overflow-hidden", viewportClass)} data-slot="carousel-content">
  <div
    data-slot="carousel-viewport"
    class={cn(
      "flex [touch-action:pan-y_pinch-zoom] -ml-(--carousel-gap)",
      "group-data-[orientation=vertical]/carousel:-mt-(--carousel-gap) group-data-[orientation=vertical]/carousel:[touch-action:pan-x_pinch-zoom] group-data-[orientation=vertical]/carousel:flex-col",
      className,
    )}
    style={style}
    {...props}
  >
    <slot />
  </div>
</div>
```

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

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

type Props = HTMLAttributes<"div"> & {
  label?: string
}

const { class: className, label = "Slide navigation", ...props } = Astro.props
---

<div
  data-slot="carousel-dots"
  role="group"
  aria-label={label}
  class={cn(
    "flex flex-wrap items-center justify-center gap-1 data-[snap-count=0]:hidden data-[snap-count=1]:hidden",
    className,
  )}
  {...props}
>
  <template>
    <button
      type="button"
      data-slot="carousel-dot"
      class="group/carousel-dot focus-visible:ring-ring ring-offset-background flex h-8 min-w-6 shrink-0 cursor-pointer touch-manipulation items-center justify-center rounded-full px-2 outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-default"
    >
      <span
        aria-hidden="true"
        class="bg-muted-foreground/30 h-2 w-2 shrink-0 rounded-full transition-[width,background-color] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] group-hover/carousel-dot:bg-muted-foreground/50 group-aria-current/carousel-dot:w-6 group-aria-current/carousel-dot:bg-primary motion-reduce:transition-none"
      />
    </button>
  </template>
</div>
```

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

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

import { cn } from "cn"

type Props = HTMLAttributes<"div">

const { class: className, ...props } = Astro.props
---

<div
  data-slot="carousel-item"
  role="group"
  aria-roledescription="slide"
  class={cn(
    "group/carousel-item min-w-0 shrink-0 grow-0 basis-full pl-(--carousel-gap)",
    "group-data-[orientation=vertical]/carousel:pt-(--carousel-gap)",
    className,
  )}
  {...props}
>
  <slot />
</div>
```

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

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

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="carousel-layer"
  class={cn("relative origin-center", className)}
  {...props}
>
  <slot />
</div>
```

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

```astro
---
import type { HTMLAttributes } from "astro/types"
import ChevronRightIcon from "@lucide/astro/icons/chevron-right"

import { cn } from "cn"
import { buttonVariants, type ButtonVariantProps } from "../button/index.ts"

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

const {
  class: className,
  variant = "outline",
  size = "icon-sm",
  disabled,
  ...props
} = Astro.props
---

<button
  type="button"
  data-slot="carousel-next"
  data-size={size}
  data-variant={variant}
  data-manual-disabled={disabled ? "true" : undefined}
  disabled={disabled}
  class={cn(buttonVariants({ variant, size }), "absolute touch-manipulation rounded-full group-data-[orientation=horizontal]/carousel:inset-y-0 group-data-[orientation=horizontal]/carousel:-right-12 group-data-[orientation=horizontal]/carousel:my-auto group-data-[orientation=vertical]/carousel:right-auto group-data-[orientation=vertical]/carousel:-bottom-12 group-data-[orientation=vertical]/carousel:left-1/2 group-data-[orientation=vertical]/carousel:-translate-x-1/2 group-data-[orientation=vertical]/carousel:translate-y-0 group-data-[orientation=vertical]/carousel:rotate-90", className)}
  {...props}
>
  <slot>
    <ChevronRightIcon aria-hidden="true" />
    <span class="sr-only">Next slide</span>
  </slot>
</button>
```

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

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

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="carousel-parallax"
  class={cn("overflow-hidden", className)}
  {...props}
>
  <div data-slot="carousel-parallax-content" class="origin-center">
    <slot />
  </div>
</div>
```

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

```astro
---
import type { HTMLAttributes } from "astro/types"
import ChevronLeftIcon from "@lucide/astro/icons/chevron-left"

import { cn } from "cn"
import { buttonVariants, type ButtonVariantProps } from "../button/index.ts"

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

const {
  class: className,
  variant = "outline",
  size = "icon-sm",
  disabled,
  ...props
} = Astro.props
---

<button
  type="button"
  data-slot="carousel-previous"
  data-size={size}
  data-variant={variant}
  data-manual-disabled={disabled ? "true" : undefined}
  disabled={disabled}
  class={cn(
    buttonVariants({ variant, size }),
    "absolute touch-manipulation rounded-full group-data-[orientation=horizontal]/carousel:inset-y-0 group-data-[orientation=horizontal]/carousel:-left-12 group-data-[orientation=horizontal]/carousel:my-auto group-data-[orientation=vertical]/carousel:-top-12 group-data-[orientation=vertical]/carousel:left-1/2 group-data-[orientation=vertical]/carousel:-translate-x-1/2 group-data-[orientation=vertical]/carousel:translate-y-0 group-data-[orientation=vertical]/carousel:rotate-90",
    className,
  )}
  {...props}
>
  <slot>
    <ChevronLeftIcon aria-hidden="true" />
    <span class="sr-only">Previous slide</span>
  </slot>
</button>
```

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

```astro
---
import type { HTMLAttributes } from "astro/types"
import type { EmblaOptionsType } from "embla-carousel"

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

type Props = CarouselOptions & HTMLAttributes<"div">

const {
  class: className,
  carouselOptions,
  orientation = "horizontal",
  effects,
  ...props
} = Astro.props

const resolvedOpts: EmblaOptionsType = {
  loop: true,
  ...carouselOptions,
  axis: orientation === "horizontal" ? "x" : "y",
}
---

<div
  data-slot="carousel"
  data-orientation={orientation}
  data-carousel-effects={effects ? JSON.stringify(effects) : undefined}
  data-carousel-options={JSON.stringify(resolvedOpts)}
  class={cn("@container/carousel group/carousel relative", className)}
  role="region"
  aria-roledescription="carousel"
  {...props}
>
  <slot />
</div>

<script>
  import { create, type CarouselController } from "./carousel.ts"

  const controllers = new Set<CarouselController>()
  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/carousel/carousel.ts

```ts
import {
    clearRootBinding,
    getRootBinding,
    getRoots,
    hasRootBinding,
    setRootBinding,
} from '@data-slot/core'
import EmblaCarousel, {
    type EmblaCarouselType,
    type EmblaOptionsType,
    type EmblaPluginType,
} from 'embla-carousel'

import { setupCarouselEffects } from './effects.ts'

import type { CarouselEffects, CarouselOptions } from './types.ts'

const ROOT_SLOT = 'carousel'

/** Browser-only setup options. Plugin functions stay in the client script. */
export type CarouselControllerOptions = Omit<
    CarouselOptions,
    'carouselOptions'
> & {
    /** Browser options can include callbacks and DOM elements. */
    carouselOptions?: EmblaOptionsType
    plugins?: EmblaPluginType[]
    /** Optional ancestor that receives arrow keys, such as a dialog panel. */
    keyboardTarget?: HTMLElement
}

export interface CarouselController {
    readonly root: HTMLElement
    readonly api: EmblaCarouselType
    destroy(): void
}

/** Read an existing instance without private element or window properties. */
export function getCarouselApi(root: Element): EmblaCarouselType | undefined {
    return getRootBinding<CarouselController>(root, ROOT_SLOT)?.api
}

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

function readOptions<T>(value: string | undefined): T {
    try {
        const parsed = JSON.parse(value ?? '{}')
        return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
            ? parsed
            : ({} as T)
    } catch {
        return {} as T
    }
}

const getDetails = (api: EmblaCarouselType) => ({
    api,
    canScrollPrev: api.canScrollPrev(),
    canScrollNext: api.canScrollNext(),
    selectedScrollSnap: api.selectedScrollSnap(),
    scrollSnapList: api.scrollSnapList(),
})

const emit = (
    root: HTMLElement,
    type: 'carousel:init' | 'carousel:select',
    api: EmblaCarouselType,
) => {
    root.dispatchEvent(
        new CustomEvent(type, {
            detail: getDetails(api),
        }),
    )
}

const syncButton = (button: Element | null, enabled: boolean) => {
    if (!(button instanceof HTMLButtonElement)) {
        return
    }

    if (button.dataset.manualDisabled === 'true') {
        button.disabled = true
        return
    }

    button.disabled = !enabled
}

/** Bind one carousel. Repeated calls return its existing controller. */
export function createCarousel(
    root: HTMLElement,
    options: CarouselControllerOptions = {},
): CarouselController {
    const existing = getRootBinding<CarouselController>(root, ROOT_SLOT)
    if (existing) return existing
    const ownedElements = <T extends Element>(selector: string) =>
        Array.from(root.querySelectorAll<T>(selector)).filter(
            (element) => element.closest('[data-slot="carousel"]') === root,
        )
    const viewport = ownedElements<HTMLElement>(
        '[data-slot="carousel-content"]',
    )[0]
    const prevButtons = ownedElements<HTMLButtonElement>(
        '[data-slot="carousel-previous"]',
    )
    const nextButtons = ownedElements<HTMLButtonElement>(
        '[data-slot="carousel-next"]',
    )
    const dotGroups = ownedElements<HTMLElement>('[data-slot="carousel-dots"]')

    if (!(viewport instanceof HTMLElement)) {
        throw new Error('Carousel requires CarouselContent.')
    }

    const orientation =
        options.orientation ?? root.dataset.orientation ?? 'horizontal'
    root.dataset.orientation = orientation
    const api = EmblaCarousel(
        viewport,
        {
            loop: true,
            ...readOptions<EmblaOptionsType>(root.dataset.carouselOptions),
            ...options.carouselOptions,
            axis: orientation === 'vertical' ? 'y' : 'x',
        },
        options.plugins,
    )
    const reducedMotion = root.ownerDocument.defaultView!.matchMedia(
        '(prefers-reduced-motion: reduce)',
    )

    const syncDots = (count: number, selected: number) => {
        for (const group of dotGroups) {
            let buttons = Array.from(
                group.querySelectorAll<HTMLButtonElement>(
                    '[data-slot="carousel-dot"]',
                ),
            )

            if (buttons.length !== count) {
                const template =
                    group.querySelector<HTMLTemplateElement>('template')
                const prototype = template?.content.querySelector('button')
                if (!prototype) continue

                const focusedIndex = buttons.findIndex(
                    (button) => button === document.activeElement,
                )
                buttons.forEach((button) => button.remove())
                buttons = Array.from({ length: count }, (_, index) => {
                    const button = prototype.cloneNode(
                        true,
                    ) as HTMLButtonElement
                    button.dataset.carouselSnap = String(index)
                    button.setAttribute(
                        'aria-label',
                        `Go to slide ${index + 1}`,
                    )
                    group.append(button)
                    return button
                })
                if (focusedIndex >= 0) {
                    buttons[Math.min(focusedIndex, count - 1)]?.focus({
                        preventScroll: true,
                    })
                }
            }

            group.dataset.snapCount = String(count)
            buttons.forEach((button, index) => {
                if (index === selected)
                    button.setAttribute('aria-current', 'true')
                else button.removeAttribute('aria-current')
                button.disabled = count < 2
            })
        }
    }

    const sync = () => {
        const details = getDetails(api)

        root.dataset.canScrollPrev = details.canScrollPrev ? 'true' : 'false'
        root.dataset.canScrollNext = details.canScrollNext ? 'true' : 'false'
        root.dataset.selectedScrollSnap = String(details.selectedScrollSnap)

        prevButtons.forEach((button) =>
            syncButton(button, details.canScrollPrev),
        )
        nextButtons.forEach((button) =>
            syncButton(button, details.canScrollNext),
        )
        syncDots(details.scrollSnapList.length, details.selectedScrollSnap)

        // A scroll snap can contain several slides. Use Embla's group mapping.
        const selectedSlides = new Set(
            api.internalEngine().slideRegistry[details.selectedScrollSnap],
        )
        api.slideNodes().forEach((slide, index) => {
            const selected = selectedSlides.has(index)
            slide.dataset.selected = String(selected)
        })

        emit(root, 'carousel:select', api)
    }

    const onPrevClick = () => {
        api.scrollPrev(reducedMotion.matches)
    }

    const onNextClick = () => {
        api.scrollNext(reducedMotion.matches)
    }

    const onClick = (event: MouseEvent) => {
        if (!(event.target instanceof Element)) return
        const button = event.target.closest(
            '[data-slot="carousel-dot"], [data-carousel-select]',
        )
        if (!button || button.closest('[data-slot="carousel"]') !== root) return

        if (
            button instanceof HTMLElement &&
            button.dataset.carouselSnap !== undefined
        ) {
            api.scrollTo(
                Number(button.dataset.carouselSnap),
                reducedMotion.matches,
            )
            return
        }

        const slide = button.closest<HTMLElement>('[data-slot="carousel-item"]')
        if (!slide) return
        const slideIndex = api.slideNodes().indexOf(slide)
        const snapIndex = api
            .internalEngine()
            .slideRegistry.findIndex((group) => group.includes(slideIndex))
        if (snapIndex >= 0) api.scrollTo(snapIndex, reducedMotion.matches)
    }

    const keyboardTarget = options.keyboardTarget ?? root
    const onKeyDown = (event: KeyboardEvent) => {
        if (
            !(event.target instanceof Element) ||
            (event.target.closest('[data-slot="carousel"]') !== root &&
                (keyboardTarget === root ||
                    event.target.closest('[data-slot="carousel"]')))
        )
            return
        if (
            event.defaultPrevented ||
            event.altKey ||
            event.ctrlKey ||
            event.metaKey
        )
            return
        if (
            event.target.closest(
                'input, textarea, select, [contenteditable="true"]',
            )
        )
            return
        const isVertical = api.internalEngine().options.axis === 'y'
        const rtl = api.internalEngine().options.direction === 'rtl'

        if (!isVertical && event.key === 'ArrowLeft') {
            event.preventDefault()
            const scroll = rtl ? api.scrollNext : api.scrollPrev
            scroll(reducedMotion.matches)
        }

        if (!isVertical && event.key === 'ArrowRight') {
            event.preventDefault()
            const scroll = rtl ? api.scrollPrev : api.scrollNext
            scroll(reducedMotion.matches)
        }

        if (isVertical && event.key === 'ArrowUp') {
            event.preventDefault()
            api.scrollPrev(reducedMotion.matches)
        }

        if (isVertical && event.key === 'ArrowDown') {
            event.preventDefault()
            api.scrollNext(reducedMotion.matches)
        }
    }

    prevButtons.forEach((button) =>
        button.addEventListener('click', onPrevClick),
    )
    nextButtons.forEach((button) =>
        button.addEventListener('click', onNextClick),
    )

    root.addEventListener('click', onClick)
    keyboardTarget.addEventListener('keydown', onKeyDown, true)

    api.on('reInit', sync)
    api.on('select', sync)

    const cleanupEffects = setupCarouselEffects(
        api,
        options.effects ??
            readOptions<CarouselEffects>(root.dataset.carouselEffects),
        reducedMotion,
    )
    let destroyed = false
    const view = root.ownerDocument.defaultView!
    const frame = view.requestAnimationFrame(() => {
        if (!destroyed) emit(root, 'carousel:init', api)
    })
    const controller: CarouselController = {
        root,
        api,
        destroy() {
            if (destroyed) return
            destroyed = true
            view.cancelAnimationFrame(frame)
            api.off('reInit', sync)
            api.off('select', sync)
            api.off('destroy', controller.destroy)
            prevButtons.forEach((button) =>
                button.removeEventListener('click', onPrevClick),
            )
            nextButtons.forEach((button) =>
                button.removeEventListener('click', onNextClick),
            )
            root.removeEventListener('click', onClick)
            keyboardTarget.removeEventListener('keydown', onKeyDown, true)
            cleanupEffects()
            clearRootBinding(root, ROOT_SLOT, controller)
            api.destroy()
        },
    }
    setRootBinding(root, ROOT_SLOT, controller)
    api.on('destroy', controller.destroy)
    sync()
    return controller
}
```

#### src/components/ui/carousel/effects.ts

```ts
import type { EmblaCarouselType } from 'embla-carousel'

import type {
    CarouselArcOptions,
    CarouselEffects,
    CarouselFadeOptions,
    CarouselParallaxOptions,
    CarouselScaleOptions,
} from './types.ts'

const clamp = (value: number, min: number, max: number) =>
    Math.min(max, Math.max(min, value))

const finite = (value: number | undefined, fallback: number) =>
    typeof value === 'number' && Number.isFinite(value) ? value : fallback

const positive = (value: number | undefined, fallback: number) => {
    const result = finite(value, fallback)
    return result > 0 ? result : fallback
}

/** Interpolate from one at the center to a minimum at the given distance. */
const tween = (distance: number, min: number, range: number) =>
    1 - (1 - min) * clamp(Math.abs(distance) / range, 0, 1)

/** Select the equivalent loop position nearest the viewport center. */
const wrap = (offset: number, length: number) =>
    length > 0 ? offset - Math.floor(offset / length + 0.5) * length : offset

/** Arc geometry only. The renderer owns loop compensation and style writes. */
function createArc(options: CarouselArcOptions = {}) {
    const radius = positive(options.radius, 2.4)
    const angle = clamp(finite(options.angle, 18), 1, 45)
    return (distance: number, width: number) => {
        const rotation = clamp(distance * angle, -90, 90)
        const radians = (rotation * Math.PI) / 180
        return {
            x: radius * width * Math.sin(radians),
            y: radius * width * (1 - Math.cos(radians)),
            rotation,
        }
    }
}

/** Opacity interpolation adapted from Embla's tween example. */
function createFade(options: CarouselFadeOptions = {}) {
    const min = clamp(finite(options.min, 0), 0, 1)
    const distance = positive(options.distance, 2.5)
    return (position: number) => tween(position, min, distance)
}

/** Scale interpolation adapted from Embla's tween example. */
function createScale(options: CarouselScaleOptions = {}) {
    const min = clamp(finite(options.min, 0.8), 0, 1)
    const distance = positive(options.distance, 1)
    return (position: number) => tween(position, min, distance)
}

/** Translation and overscan for clipped content, adapted from Embla's example. */
function createParallax(options: CarouselParallaxOptions = {}) {
    const amount = clamp(finite(options.amount, 0.2), 0, 1)
    return (distance: number, size: number) => ({
        offset: -clamp(distance, -1, 1) * amount * size,
        scale: 1 + amount * 2,
    })
}

const bindings = new WeakMap<EmblaCarouselType, () => void>()
const config = <T>(value: boolean | T): T | undefined =>
    typeof value === 'boolean' ? undefined : value

type StyleProperty =
    | 'transform'
    | 'opacity'
    | 'z-index'
    | 'position'
    | 'transition'

type SavedStyle = { value: string; priority: string }

/**
 * Bind one effect renderer to an Embla instance. Calling it again replaces the
 * previous effects. Return a cleanup function; destroy also runs it.
 * The scroll interpolation follows Embla's v8 tween examples:
 * https://www.embla-carousel.com/docs/v8/examples/predefined
 */
export function setupCarouselEffects(
    api: EmblaCarouselType,
    options: CarouselEffects = {},
    reducedMotion = api
        .internalEngine()
        .ownerWindow.matchMedia('(prefers-reduced-motion: reduce)'),
): () => void {
    bindings.get(api)?.()
    if (!options.arc && !options.scale && !options.fade && !options.parallax)
        return () => {}

    const arc = options.arc ? createArc(config(options.arc)) : undefined
    const scale = options.scale ? createScale(config(options.scale)) : undefined
    const fade = options.fade ? createFade(config(options.fade)) : undefined
    const parallax = options.parallax
        ? createParallax(config(options.parallax))
        : undefined
    let engine = api.internalEngine()
    let destroyed = false
    let slides: ReturnType<typeof measure>[] = []
    let loopOffsets = new Map<number, () => number>()
    const styles = new Map<HTMLElement, Map<StyleProperty, SavedStyle>>()

    const write = (
        node: HTMLElement,
        property: StyleProperty,
        value: string,
    ) => {
        let saved = styles.get(node)
        if (!saved) styles.set(node, (saved = new Map()))
        if (!saved.has(property))
            saved.set(property, {
                value: node.style.getPropertyValue(property),
                priority: node.style.getPropertyPriority(property),
            })
        if (node.style.getPropertyValue(property) !== value)
            node.style.setProperty(property, value)
    }
    const clear = () => {
        for (const [node, properties] of styles) {
            for (const [property, saved] of properties) {
                if (saved.value)
                    node.style.setProperty(
                        property,
                        saved.value,
                        saved.priority,
                    )
                else node.style.removeProperty(property)
            }
        }
        styles.clear()
        for (const { layer, inert } of slides) {
            if (layer && layer.inert !== inert) layer.inert = inert
        }
    }
    const ownPart = (slide: HTMLElement, slot: string) =>
        Array.from(
            slide.querySelectorAll<HTMLElement>(`[data-slot="${slot}"]`),
        ).find((node) => node.closest('[data-slot="carousel-item"]') === slide)

    function measure(slide: HTMLElement) {
        const layer = ownPart(slide, 'carousel-layer')
        const content = ownPart(slide, 'carousel-parallax-content')
        return {
            slide,
            layer,
            content,
            width: layer?.offsetWidth ?? 0,
            contentSize:
                engine.options.axis === 'x'
                    ? (content?.offsetWidth ?? 0)
                    : (content?.offsetHeight ?? 0),
            inert: layer?.inert ?? false,
        }
    }

    const update = () => {
        if (destroyed || reducedMotion.matches) return
        const { axis, containerRect, slideRects, offsetLocation } = engine
        const viewSize = axis.measureSize(containerRect)
        if (!viewSize) return
        const hasArc = !!arc && engine.options.axis === 'x'
        const loopLength = engine.options.loop ? engine.limit.length : 0
        const location = offsetLocation.get()

        slides.forEach(
            ({ slide, layer, content, width, contentSize, inert }, index) => {
                const rect = slideRects[index]
                if (!rect) return
                const size = axis.measureSize(rect)
                if (!size) return
                const offset =
                    axis.direction(
                        rect[axis.startEdge] - containerRect[axis.startEdge],
                    ) +
                    size / 2 +
                    location -
                    viewSize / 2
                const renderedOffset = axis.direction(
                    offset + (loopOffsets.get(index)?.() ?? 0),
                )
                // The nearest visual copy is independent of Embla's flat loop boundary.
                // Compensate on the inner layer when Embla relocates the outer slide.
                const visualOffset =
                    hasArc && loopLength
                        ? axis.direction(wrap(offset, loopLength))
                        : renderedOffset
                const distance = visualOffset / size

                if (layer && (hasArc || scale || fade)) {
                    const transforms: string[] = []
                    let opacity = fade?.(distance) ?? 1
                    if (hasArc) {
                        const point = arc!(distance, width)
                        transforms.push(
                            `translate3d(${point.x - renderedOffset}px, ${point.y}px, 0) rotate(${point.rotation}deg)`,
                        )
                        write(slide, 'position', 'relative')
                        write(
                            slide,
                            'z-index',
                            String(Math.round(100 - Math.abs(distance) * 10)),
                        )
                        // Hide the seam before the nearest copy switches sides. This
                        // also covers small radii where both ends fit in the viewport.
                        if (loopLength)
                            opacity *= clamp(
                                (loopLength / 2 - Math.abs(visualOffset)) /
                                    size,
                                0,
                                1,
                            )
                    }
                    if (scale) transforms.push(`scale(${scale(distance)})`)
                    if (transforms.length) {
                        write(layer, 'transition', 'none')
                        write(layer, 'transform', transforms.join(' '))
                    }
                    if (fade || (hasArc && loopLength)) {
                        write(layer, 'transition', 'none')
                        write(layer, 'opacity', String(opacity))
                        const hidden = inert || opacity === 0
                        if (layer.inert !== hidden) layer.inert = hidden
                    }
                }
                if (content && parallax) {
                    const value = parallax(distance, contentSize)
                    const x = engine.options.axis === 'x' ? value.offset : 0
                    const y = engine.options.axis === 'y' ? value.offset : 0
                    write(content, 'transition', 'none')
                    write(
                        content,
                        'transform',
                        `translate3d(${x}px, ${y}px, 0) scale(${value.scale})`,
                    )
                }
            },
        )
    }

    const refresh = () => {
        clear()
        engine = api.internalEngine()
        slides = api.slideNodes().map(measure)
        loopOffsets = new Map(
            engine.options.loop
                ? engine.slideLooper.loopPoints.map((point) => [
                      point.index,
                      point.target,
                  ])
                : [],
        )
        update()
    }
    const onMotionChange = () => {
        clear()
        update()
    }
    const cleanup = () => {
        if (destroyed) return
        destroyed = true
        api.off('scroll', update)
        api.off('settle', update)
        api.off('slideFocus', update)
        api.off('reInit', refresh)
        api.off('destroy', cleanup)
        reducedMotion.removeEventListener('change', onMotionChange)
        clear()
        if (bindings.get(api) === cleanup) bindings.delete(api)
    }

    bindings.set(api, cleanup)
    api.on('scroll', update)
    api.on('settle', update)
    api.on('slideFocus', update)
    api.on('reInit', refresh)
    api.on('destroy', cleanup)
    reducedMotion.addEventListener('change', onMotionChange)
    refresh()
    return cleanup
}
```

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

```ts
export type {
    EmblaCarouselType as CarouselApi,
    EmblaPluginType as CarouselPlugin,
} from 'embla-carousel'

export type {
    CarouselArcOptions,
    CarouselContentProps,
    CarouselEffects,
    CarouselEmblaOptions,
    CarouselFadeOptions,
    CarouselOptions,
    CarouselParallaxOptions,
    CarouselScaleOptions,
} from './types.ts'

export { create, createCarousel, getCarouselApi } from './carousel.ts'
export type {
    CarouselController,
    CarouselControllerOptions,
} from './carousel.ts'
export { setupCarouselEffects } from './effects.ts'

export { default as Carousel } from './carousel.astro'
export { default as CarouselContent } from './carousel-content.astro'
export { default as CarouselItem } from './carousel-item.astro'
export { default as CarouselLayer } from './carousel-layer.astro'
export { default as CarouselParallax } from './carousel-parallax.astro'
export { default as CarouselDots } from './carousel-dots.astro'
export { default as CarouselPrevious } from './carousel-previous.astro'
export { default as CarouselNext } from './carousel-next.astro'
```

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

```ts
import type { EmblaOptionsType } from 'embla-carousel'

type CarouselAlign = Extract<EmblaOptionsType['align'], string>

type SerializableEmblaOptions = Pick<
    EmblaOptionsType,
    | 'active'
    | 'containScroll'
    | 'direction'
    | 'slidesToScroll'
    | 'dragFree'
    | 'dragThreshold'
    | 'inViewThreshold'
    | 'loop'
    | 'skipSnaps'
    | 'duration'
    | 'startIndex'
>

interface CarouselEmblaBaseOptions extends SerializableEmblaOptions {
    /** Enable the carousel's controls. @default true */
    active?: boolean
    /** Prevent the carousel from scrolling outside of its container. @default true */
    containScroll?: NonNullable<EmblaOptionsType['containScroll']>
    /** The direction of the carousel. @default 'ltr' (left to right) */
    direction?: 'ltr' | 'rtl'
    /** The number of slides to scroll on a single previous/next button click. @default 1 */
    slidesToScroll?: NonNullable<EmblaOptionsType['slidesToScroll']>
    /** Allow the user to drag the carousel freely. @default false */
    dragFree?: boolean
    /** The percentage of the slide that must be dragged to be considered a drag. @default 0.5 */
    dragThreshold?: number
    /** The percentage of the slide that must be visible to be considered in view. @default 0.5 */
    inViewThreshold?: NonNullable<EmblaOptionsType['inViewThreshold']>
    /** Return to the starting slide when the end is reached. @default false */
    loop?: boolean
    /** Skip the snap points when the carousel is at the start or end. @default false */
    skipSnaps?: boolean
    /** The duration of the animation in milliseconds. @default 1000 */
    duration?: number
    /** The index of the first slide to show. @default 0 */
    startIndex?: number
    /** Slide alignment. Callback functions require browser setup. */
    align?: CarouselAlign
    /** Enable drag handling. @default true */
    watchDrag?: boolean
    /** Observe carousel size changes. @default true */
    watchResize?: boolean
    /** Observe added or removed slides. @default true */
    watchSlides?: boolean
    /** Scroll to focused slide content. @default true */
    watchFocus?: boolean
}

/** Embla options that can pass through JSON from Astro to the browser. */
export type CarouselEmblaOptions = CarouselEmblaBaseOptions & {
    /** Media queries with the same options, without nested breakpoints. */
    breakpoints?: Record<string, CarouselEmblaBaseOptions>
}

/** Geometry for a horizontal arc. Scale and fade are separate effects. */
export type CarouselArcOptions = {
    /** Circle radius in layer widths. Must be positive. @default 2.4 */
    radius?: number
    /** Rotation per slide width, in degrees. Range: 1–45. @default 18 */
    angle?: number
}

/** Scale of a layer as it moves away from the viewport center. */
export type CarouselScaleOptions = {
    /** Smallest scale. Range: 0–1. @default 0.8 */
    min?: number
    /** Distance to the smallest scale, in slide widths. @default 1 */
    distance?: number
}

/** Opacity of a layer as it moves away from the viewport center. */
export type CarouselFadeOptions = {
    /** Lowest opacity. Range: 0–1. @default 0 */
    min?: number
    /** Distance to the lowest opacity, in slide widths. @default 2.5 */
    distance?: number
}

/** Movement of content inside a clipped CarouselParallax part. */
export type CarouselParallaxOptions = {
    /** Maximum translation as a fraction of the content size. Range: 0–1. @default 0.2 */
    amount?: number
}

/** Optional effects. `true` uses the defaults; omitted effects stay off. */
export type CarouselEffects = {
    /** Position and rotate CarouselLayer parts on a horizontal arc. */
    arc?: boolean | CarouselArcOptions
    /** Scale CarouselLayer parts. */
    scale?: boolean | CarouselScaleOptions
    /** Fade CarouselLayer parts. Fully transparent layers become inert. */
    fade?: boolean | CarouselFadeOptions
    /** Move content inside CarouselParallax parts. Supports either axis. */
    parallax?: boolean | CarouselParallaxOptions
}

/** Props for the carousel root, minus HTML attributes. */
export type CarouselOptions = {
    /** JSON-compatible Embla options. Orientation and Astro parts control the axis and elements. */
    carouselOptions?: CarouselEmblaOptions
    /** Scroll axis for the carousel. @default "horizontal" */
    orientation?: 'horizontal' | 'vertical'
    /** Independent effects applied to the optional inner parts. */
    effects?: CarouselEffects
}

/** Layout props for the carousel track and its clipping viewport. */
export type CarouselContentProps = {
    /** CSS gap value for space between items. @default "1rem" */
    gap?: string
    /** Classes for the clipping viewport, such as padding for an arc. */
    viewportClass?: string
}
```

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.


## About

The carousel is built with
[Embla Carousel](https://www.embla-carousel.com/) for motion and swipe. The
Astro components follow the same composition as shadcn/ui.

## Usage

```astro
---
import {
	Carousel,
	CarouselContent,
	CarouselDots,
	CarouselItem,
	CarouselNext,
	CarouselPrevious,
} from "@/components/ui/carousel"

---
<Carousel>
  <CarouselContent>
    <CarouselItem>...</CarouselItem>
    <CarouselItem>...</CarouselItem>
    <CarouselItem>...</CarouselItem>
  </CarouselContent>
  <CarouselPrevious />
  <CarouselNext />
</Carousel>
```

## Composition

Arrange the parts as shown for a `Carousel`:

```text
Carousel
├── CarouselContent
│   ├── CarouselItem
│   └── CarouselItem
├── CarouselPrevious
└── CarouselNext
```

## Examples

### Sizes

To set the size of the items, use the `basis` utility classes on
`<CarouselItem />`.

```astro
---
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"

const items = Array.from({ length: 5 }, (_, index) => index + 1)
---

<Carousel class="w-full max-w-xl">
  <CarouselContent>
    {items.map((item) => (
      <CarouselItem class="basis-1/2">
        <div class="h-24 w-full bg-muted"></div>
      </CarouselItem>
    ))}
  </CarouselContent>
  <CarouselPrevious />
  <CarouselNext />
</Carousel>
```

```astro
<!-- 33% of the carousel width -->
<Carousel>
  <CarouselContent>
    <CarouselItem class="basis-1/3">...</CarouselItem>
    <CarouselItem class="basis-1/3">...</CarouselItem>
    <CarouselItem class="basis-1/3">...</CarouselItem>
  </CarouselContent>
</Carousel>
```

```astro
<!-- 50% on small screens and 33% on larger screens -->
<Carousel>
  <CarouselContent>
    <CarouselItem class="md:basis-1/2 lg:basis-1/3">...</CarouselItem>
    <CarouselItem class="md:basis-1/2 lg:basis-1/3">...</CarouselItem>
    <CarouselItem class="md:basis-1/2 lg:basis-1/3">...</CarouselItem>
  </CarouselContent>
</Carousel>
```

### Spacing

Set `gap` on `<CarouselContent />` to set the space between items. The default is
`1rem`. This prop sets `--carousel-gap`, which the content and items use for
their spacing.

```astro
---
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
---

<Carousel class="w-full max-w-xl">
  <CarouselContent gap="clamp(0.5rem, 2cqi, 1rem)">
    <CarouselItem>
      <div class="bg-muted flex aspect-video items-center justify-center rounded-md">
        Slide 1
      </div>
    </CarouselItem>
    <CarouselItem>
      <div class="bg-muted flex aspect-video items-center justify-center rounded-md">
        Slide 2
      </div>
    </CarouselItem>
    <CarouselItem>
      <div class="bg-muted flex aspect-video items-center justify-center rounded-md">
        Slide 3
      </div>
    </CarouselItem>
    <CarouselItem>
      <div class="bg-muted flex aspect-video items-center justify-center rounded-md">
        Slide 4
      </div>
    </CarouselItem>
  </CarouselContent>
  <CarouselPrevious />
  <CarouselNext />
</Carousel>
```

```astro
<Carousel>
  <CarouselContent gap="1.5rem">
    <CarouselItem>...</CarouselItem>
    <CarouselItem>...</CarouselItem>
    <CarouselItem>...</CarouselItem>
  </CarouselContent>
</Carousel>
```

Use a CSS value such as `clamp()` when the gap must change with the viewport:

```astro
<Carousel>
  <CarouselContent gap="clamp(0.5rem, 2vw, 1rem)">
    <CarouselItem>...</CarouselItem>
    <CarouselItem>...</CarouselItem>
    <CarouselItem>...</CarouselItem>
  </CarouselContent>
</Carousel>
```

### Scale and fade

Effects are optional. A normal `CarouselItem` has one default slot and accepts
any content. Put content inside `CarouselLayer` to apply scale, fade, or arc
movement. This works with text, cards, buttons, and images.

```astro
---
import { Card, CardContent } from "@/components/ui/card"
import {
  Carousel,
  CarouselContent,
  CarouselDots,
  CarouselItem,
  CarouselLayer,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"

const steps = ["Plan", "Sketch", "Build", "Test", "Refine", "Share", "Review"]
---

<Carousel
  effects={{ scale: { min: 0.8 }, fade: { min: 0.35, distance: 2 } }}
  carouselOptions={{ loop: true, align: "center", containScroll: false }}
  class="w-full max-w-3xl"
  aria-label="Project steps"
>
  <CarouselContent viewportClass="py-4">
    {steps.map((step, index) => (
      <CarouselItem
        class="basis-3/4 @min-xl/carousel:basis-1/3"
        aria-label={`${index + 1} of ${steps.length}`}
      >
        <CarouselLayer>
          <Card>
            <CardContent class="flex aspect-square flex-col items-center justify-center gap-3 p-6">
              <span class="text-muted-foreground text-sm">
                Step {index + 1}
              </span>
              <h3 class="text-2xl font-semibold">{step}</h3>
            </CardContent>
          </Card>
        </CarouselLayer>
      </CarouselItem>
    ))}
  </CarouselContent>
  <div class="mt-4 flex items-center justify-between gap-4">
    <CarouselPrevious class="static" />
    <CarouselDots />
    <CarouselNext class="static" />
  </div>
</Carousel>
```

```astro
<Carousel effects={{ scale: { min: 0.8 }, fade: { min: 0.35, distance: 2 } }}>
  <CarouselContent>
    <CarouselItem>
      <CarouselLayer>
        <article>Any slide content</article>
      </CarouselLayer>
    </CarouselItem>
    <!-- Add more items. -->
  </CarouselContent>
</Carousel>
```

Each effect can be `true` for its defaults, an options object, or `false`.
Omitted effects stay off. `scale.distance` and `fade.distance` are distances from
the viewport center in slide widths. They work on both axes, including grouped
slides and slides with different widths.

### Parallax

Use `effects.parallax` with `CarouselParallax`. This part clips its inner content.
The renderer translates and enlarges that content to keep the edges covered.
It uses the carousel's axis and direction. Put it inside `CarouselLayer` to
combine parallax with scale, fade, or arc movement.

```astro
---
import {
  Carousel,
  CarouselContent,
  CarouselDots,
  CarouselItem,
  CarouselParallax,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
import { Image } from "astro:assets"

import water from "@/assets/wizard/wizard-overlooking-water.png"
import moon from "@/assets/wizard/wizard-on-moon.jpeg"
import clouds from "@/assets/wizard/wizard-above-clouds.jpeg"
import wizard from "@/assets/wizard/automation-design.png"
import portal from "@/assets/images/the-portal.png"

const images = [
  { image: water, alt: "A wizard looks out over the water." },
  { image: moon, alt: "A wizard stands on the moon." },
  { image: clouds, alt: "A wizard stands above the clouds." },
  { image: wizard, alt: "A wizard performing automations" },
  { image: portal, alt: "A glowing portal in the distance" },
]
---

<Carousel
  effects={{ parallax: { amount: 0.2 } }}
  carouselOptions={{ loop: true, align: "center", containScroll: false }}
  class="w-full max-w-4xl"
  aria-label="Wizard travels"
>
  <CarouselContent gap="0.5rem">
    {images.map(({ image, alt }, index) => (
      <CarouselItem
        class="basis-[70%] @min-4xl/carousel:basis-1/2"
        aria-label={`${index + 1} of ${images.length}`}
      >
        <button
          type="button"
          data-carousel-select
          aria-label={`Show image ${index + 1}`}
          class="focus-visible:ring-ring block w-full cursor-pointer rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-inset"
        >
          <CarouselParallax class="rounded-xl">
            <Image
              src={image}
              alt={alt}
              class="aspect-square w-full object-cover"
              loading="eager"
              decoding="async"
            />
          </CarouselParallax>
        </button>
      </CarouselItem>
    ))}
  </CarouselContent>
  <div class="mt-6 flex items-center justify-between gap-4">
    <div class="flex items-center gap-2">
      <CarouselPrevious class="static" />
      <CarouselNext class="static" />
    </div>
    <CarouselDots class="justify-end" />
  </div>
</Carousel>
```

```astro
<Carousel effects={{ parallax: { amount: 0.2 } }}>
  <CarouselContent>
    <CarouselItem>
      <CarouselParallax class="rounded-xl">
        <img src="/project.jpg" alt="A restored deck." class="aspect-square w-full object-cover" />
      </CarouselParallax>
    </CarouselItem>
    <!-- Add more items. -->
  </CarouselContent>
</Carousel>
```

`amount` is the maximum translation as a fraction of the content size. Its
default is `0.2`. The part can contain any content; it has no image slot.

### Arc

Use `effects.arc` for a curved row. The arc changes position and rotation.
Scale and fade remain separate options.

```astro
---
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselLayer,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
import street from "@/assets/wizard/wizard-small-street.png"
import moon from "@/assets/wizard/wizard-on-moon.jpeg"
import clouds from "@/assets/wizard/wizard-above-clouds.jpeg"
import town from "@/assets/wizard/wizard-overlooking-town.png"
import future from "@/assets/images/taking-in-the-future.png"
import beach from "@/assets/images/beach-on-alien-planet.png"
import planet from "@/assets/wizard/wizard-in-field-looking-at-planet.png"
import { Image } from "astro:assets"

const images = [
  { image: street, alt: "A wizard on a narrow street between tall buildings." },
  { image: moon, alt: "A wizard stands on the moon." },
  { image: clouds, alt: "A robot stands above the clouds." },
  { image: town, alt: "A wizard looks over a town." },
  { image: future, alt: "A figure taking in a distant future skyline." },
  { image: beach, alt: "A beach on an alien planet under a bright sky." },
  { image: planet, alt: "A wizard looks at a planet." },
]
---

<Carousel
  effects={{
    arc: { radius: 2.4, angle: 18 },
    scale: { min: 0.5, distance: 2.5 },
    fade: { distance: 2.5 },
  }}
  carouselOptions={{
    loop: true,
    align: "center",
    containScroll: false,
    slidesToScroll: 1,
  }}
  class="w-full max-w-4xl"
  aria-label="Wizard travels in an arc"
>
  <CarouselContent viewportClass="pt-6 pb-12 @min-sm/carousel:pt-10 @min-sm/carousel:pb-24">
    {images.map(({ image, alt }, index) => (
      <CarouselItem
        class="basis-5/12"
        aria-label={`${index + 1} of ${images.length}`}
      >
        <CarouselLayer class="overflow-hidden rounded-xl">
          <button
            type="button"
            data-carousel-select
            aria-label={`Show image ${index + 1}`}
            class="focus-visible:ring-ring block w-full cursor-pointer rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-inset"
          >
            <Image
              src={image}
              alt={alt}
              class="aspect-4/5 w-full object-cover"
              loading="eager"
              decoding="async"
            />
          </button>
        </CarouselLayer>
      </CarouselItem>
    ))}
  </CarouselContent>
  <div class="mt-2 flex items-center justify-between gap-4">
    <CarouselPrevious class="static" />
    <CarouselNext class="static" />
  </div>
</Carousel>
```

```astro
<Carousel
  effects={{
    arc: { radius: 2.4, angle: 18 },
    scale: { min: 0.5, distance: 2.5 },
    fade: { distance: 2.5 },
  }}
  carouselOptions={{ loop: true, align: "center", containScroll: false }}
  aria-label="Travel photos"
>
  <CarouselContent viewportClass="pt-6 pb-24">
    <CarouselItem class="basis-5/12">
      <CarouselLayer class="overflow-hidden rounded-xl">
        <button type="button" data-carousel-select aria-label="Show coast photo" class="block w-full">
          <img src="/coast.jpg" alt="A rocky coast." class="aspect-[4/5] w-full object-cover" />
        </button>
      </CarouselLayer>
    </CarouselItem>
    <!-- Add more items. -->
  </CarouselContent>
</Carousel>
```

The radius is in layer widths. The angle is in degrees per slide width.
The defaults are `2.4` and `18`. The radius must be positive; the angle is limited
to 1–45 degrees. Increase viewport padding for a deeper arc.

The renderer keeps the visible arc position continuous when Embla relocates a
slide for looping. At the opposite end of the loop, it fades a layer over one
slide width before that layer switches sides. This prevents a visible jump,
including when a small radius puts both ends inside the viewport.

Arc movement supports horizontal carousels. On a vertical carousel, other enabled
effects still work. Reduced motion removes all effects and makes button and
keyboard navigation instant. Fully transparent layers become inert. Cleanup
restores the caller's inline styles and original inert state.

### Selection styling and overlays

Items expose `data-selected` and the `group/carousel-item` class. Compose an
overlay as ordinary content inside `CarouselLayer`. For example, use
`group-data-[selected=false]/carousel-item:invisible` to hide an overlay and its
controls on unselected slides. Blur, dimming, rounding, and overlay placement
belong in this composition.

See [Projects Carousel](/blocks/gallery) for a complete section with these styles.
The old `variant`, root `arc` prop, and item `image` and `overlay` slots have been
replaced by `effects` and the optional parts.

### Dot navigation and selection

Put `CarouselDots` inside `Carousel`. It creates one labelled button for each
scroll position and sets `aria-current="true"` on the selected button. The dots
update after a resize or a slide change. They also support grouped slides.
Set `label` to change the navigation group's accessible name.

The active dot expands into a pill. Its width and color change over 300 ms.
Reduced motion makes this change instant. The button grows with the dot and
keeps padding around it for pointer input and keyboard focus.

The client script sets `data-selected="true"` on items in the selected group.

To select a slide from a button, put `data-carousel-select` on that button
inside the item. Keep overlay links separate from that button.

## API Reference

Read the [installed source](/r/carousel.json) and the
[Embla v8 API](https://www.embla-carousel.com/docs/v8/api/methods).

<AutoTypeTable
    path="../../packages/ui/src/components/ui/carousel/types.ts"
    name="CarouselOptions"
/>
<AutoTypeTable
    path="../../packages/ui/src/components/ui/carousel/types.ts"
    name="CarouselEmblaOptions"
/>
<AutoTypeTable
    path="../../packages/ui/src/components/ui/carousel/types.ts"
    name="CarouselContentProps"
/>
<AutoTypeTable
    path="../../packages/ui/src/components/ui/carousel/types.ts"
    name="CarouselEffects"
/>
<AutoTypeTable
    path="../../packages/ui/src/components/ui/carousel/types.ts"
    name="CarouselArcOptions"
/>
<AutoTypeTable
    path="../../packages/ui/src/components/ui/carousel/types.ts"
    name="CarouselScaleOptions"
/>
<AutoTypeTable
    path="../../packages/ui/src/components/ui/carousel/types.ts"
    name="CarouselFadeOptions"
/>
<AutoTypeTable
    path="../../packages/ui/src/components/ui/carousel/types.ts"
    name="CarouselParallaxOptions"
/>

### Embla options in Astro

`carouselOptions` accepts JSON-compatible values, including `loop`, `duration`,
`slidesToScroll`, and media-query `breakpoints`. Set `align` to `"start"`, `"center"`,
or `"end"` inside this object. The `watchDrag`, `watchFocus`, `watchResize`, and
`watchSlides` options accept booleans. Breakpoints use the same options and cannot
contain another `breakpoints` object.

Callbacks and DOM elements cannot pass through the HTML data attribute. Use
`orientation` for the axis and the Astro parts for the container and slides.
Keep callback options in a browser script through the client API below.

### Image loading

Use `loading="lazy"` on images outside the initial view. Astro's `Image` uses
this value by default. Use `priority` for an important image visible when the
page opens. The browser can load nearby slides before they become visible;
lazy loading does not limit downloads to the selected slide.

### Client setup

The Astro component calls `create()` from `carousel/carousel.ts`. It binds each
unbound root once and destroys its controllers on removal or an Astro page swap.
There is no carousel state on `window`.

For manually rendered markup, `createCarousel(root, options)` returns
`{ root, api, destroy }`. A repeated call returns the existing controller.
Client options accept `carouselOptions`, `orientation`, `effects`, and Embla
`plugins`. Browser `carouselOptions` accepts the full `EmblaOptionsType`, including
callbacks and DOM elements. The root `orientation` still sets the base axis.
Plugin functions stay in the client script; do not pass them through Astro
frontmatter props. Call `destroy()` before binding new controller options.

`getCarouselApi(root)` reads an existing Embla instance. The same shared effects
setup is available to client scripts:

```ts
import { setupCarouselEffects } from "@/components/ui/carousel/effects.ts"

// api is an initialized Embla instance, for example from carousel:init.
const cleanup = setupCarouselEffects(api, {
    arc: { radius: 2.4, angle: 18 },
    scale: { min: 0.8 },
})
```

Calling this setup again replaces the earlier effects. Its cleanup removes
listeners and restores styles. Destroying Embla also cleans up the effects.
Keep caller transforms on another element: the effect renderer owns transforms
on `CarouselLayer` and the inner `CarouselParallax` content while active.

### Events

The carousel root emits these events. Both events use the same detail.

#### Outbound events

| Event             | Detail                                                                                                                             |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `carousel:init`   | `{ api: EmblaCarouselType, canScrollPrev: boolean, canScrollNext: boolean, selectedScrollSnap: number, scrollSnapList: number[] }` |
| `carousel:select` | `{ api: EmblaCarouselType, canScrollPrev: boolean, canScrollNext: boolean, selectedScrollSnap: number, scrollSnapList: number[] }` |

## When to use Carousel

Put related slides inside CarouselContent and keep each slide in a CarouselItem. Pass Embla options through the `carouselOptions` prop. Choose an orientation and slide width that match the content rather than forcing all content into one layout.

## Keyboard and behavior

The client script starts Embla for drag and swipe behavior. Provide labelled previous and next controls for people who cannot drag. Essential content should remain understandable without swiping through an unexplained sequence.

## Theme and layout

Set image dimensions to reduce layout movement and check the last slide at narrow widths. Theme tokens style the controls; slide composition stays in your Astro markup. Autoplay is not supplied by the base component.
