---
title: Image Compare for Astro
description: "Astro before-and-after pictures with a pointer and keyboard divider."
seo:
    title: Image Compare for Astro | Shadcn & Tailwind CSS
related:
    - /components/slider
    - /components/lightbox
sidebar:
    label: "Image Compare"
    badge: "New"
---

```astro
---
import { getImage } from "astro:assets"
import {
  ImageCompareHandle,
  ImageCompareImage,
  ImageCompare,
} from "@/components/ui/image-compare"
import winterOrion from "@/assets/images/winter-landscape-orion.png"
import winterTheta from "@/assets/images/winter-landscape-theta.png"

const [orion, theta] = await Promise.all([
  getImage({ src: winterOrion, width: 1200, format: "webp" }),
  getImage({ src: winterTheta, width: 1200, format: "webp" }),
])
---

<ImageCompare class="rounded-xl" label="Amount of the Orion winter plate shown">
  <ImageCompareImage
    src={theta.src}
    alt="A winter valley in clearer light."
    width={theta.attributes.width}
    height={theta.attributes.height}
  />
  <ImageCompareImage
    src={orion.src}
    alt="The same winter valley under a pale sky."
    width={orion.attributes.width}
    height={orion.attributes.height}
    clip
  />
  <span class="bg-background/80 text-foreground pointer-events-none absolute top-4 left-4 z-20 rounded px-3 py-1 text-sm">
    Orion
  </span>
  <span class="bg-background/80 text-foreground pointer-events-none absolute top-4 right-4 z-20 rounded px-3 py-1 text-sm">
    Theta
  </span>
  <ImageCompareHandle />
</ImageCompare>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/image-compare
```

### Manual

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

No extra packages are required.

#### src/components/ui/image-compare/image-compare-handle.astro

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

import { cn } from "cn"
import GripVerticalIcon from "@lucide/astro/icons/grip-vertical"

/**
 * Pointer drag surface and divider between the two pictures.
 * Div attributes such as `class` pass through.
 * The default slot replaces the grip icon.
 * Keyboard input stays on the range control in `ImageCompare`.
 */
type Props = HTMLAttributes<"div">

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

<div
  data-slot="image-compare-handle"
  aria-hidden="true"
  class={cn(
    "pointer-events-auto absolute inset-y-0 left-(--image-compare-position,50%) z-30 flex w-8 -translate-x-1/2 cursor-grab touch-none items-center justify-center",
    "group-data-[dragging=true]/image-compare:cursor-grabbing",
    className,
  )}
  {...props}
>
  <span
    class="block w-1 h-full bg-background absolute inset-0 mx-auto"
    aria-hidden="true"
    data-slot="image-compare-handle-line"
  />
  <span
    class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-background px-0.5 py-2 [&_svg:not([class*='size-'])]:size-4"
    title="Slide to compare images"
  >
    <slot>
      <GripVerticalIcon class="text-foreground/72 group-hover/image-compare:text-foreground" />
    </slot>
  </span>
</div>
```

#### src/components/ui/image-compare/image-compare-image.astro

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

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

/** Image attributes pass through. `src`, `alt`, and `clip` come from `ImageCompareImageProps`. */
type Props = Omit<HTMLAttributes<"img">, "src" | "alt"> & ImageCompareImageProps

const {
  class: className,
  src,
  alt,
  width,
  height,
  clip = false,
  draggable = false,
  ...props
} = Astro.props

/**
 * An imported picture carries its own pixel size.
 * A plain address uses the 16:9 fallback unless the caller sets a size.
 * `draggable` is the string "true" or "false". A boolean false would omit the attribute.
 */
const resolvedSrc = typeof src === "string" ? src : src.src
const resolvedWidth = width ?? (typeof src === "string" ? 1200 : src.width)
const resolvedHeight = height ?? (typeof src === "string" ? 675 : src.height)
const imageDraggable =
  draggable === true || draggable === "true" ? "true" : "false"
---

<img
  data-slot="image-compare-image"
  data-clip={clip ? "true" : undefined}
  src={resolvedSrc}
  alt={alt}
  width={resolvedWidth}
  height={resolvedHeight}
  draggable={imageDraggable}
  class={cn(
    "pointer-events-none absolute inset-0 size-full object-cover",
    clip ? "image-compare-clip z-10" : "z-0",
    className,
  )}
  {...props}
/>

<style>
  /* Reveal the left portion. The root sets --image-compare-position. */
  .image-compare-clip {
    clip-path: inset(0 calc(100% - var(--image-compare-position, 50%)) 0 0);
  }
</style>
```

#### src/components/ui/image-compare/image-compare.astro

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

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

/**
 * Comparison frame.
 * Place two `ImageCompareImage` parts and one `ImageCompareHandle` in the slot.
 * Div attributes pass through. `defaultValue` and `label` come from `ImageCompareProps`.
 */
type Props = HTMLAttributes<"div"> & ImageCompareProps

const {
  class: className,
  defaultValue = 50,
  label = "Amount of the clipped image shown",
  style,
  ...props
} = Astro.props

/**
 * Keep the divider inside the frame.
 * A non-numeric value falls back to the center.
 */
const position = Number.isFinite(defaultValue)
  ? Math.min(100, Math.max(0, defaultValue))
  : 50

/** String form so a value of 0 stays on the range control. */
const positionValue = String(position)
const positionStyle = `--image-compare-position:${positionValue}%`
const mergedStyle =
  typeof style === "string"
    ? `${style};${positionStyle}`
    : { ...style, "--image-compare-position": `${positionValue}%` }
---

<div
  data-slot="image-compare"
  data-dragging="false"
  style={mergedStyle}
  class={cn(
    "group/image-compare relative block aspect-video w-full touch-pan-y overflow-hidden rounded-2xl bg-background select-none",
    className,
  )}
  {...props}
>
  <slot />
  <input
    data-slot="image-compare-input"
    type="range"
    min={0}
    max={100}
    step={0.01}
    value={positionValue}
    aria-label={label}
    class="pointer-events-none sr-only"
  />
</div>

<script>
  import { type ImageCompareController, create } from "./image-compare.ts"

  const controllers: ImageCompareController[] = []

  const initialize = () => controllers.push(...create())

  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>
```

#### src/components/ui/image-compare/image-compare.ts

```ts
const rootSelector = '[data-slot="image-compare"]'
const controllers = new WeakMap<HTMLElement, ImageCompareController>()

export interface ImageCompareController {
    destroy(): void
    updatePosition(): void
    startDrag(event: PointerEvent): void
    endDrag(event: PointerEvent): void
    moveDrag(event: PointerEvent): void
}

/** Bind each unbound comparison in the scope. */
export function create(scope: ParentNode = document): ImageCompareController[] {
    const roots = [...scope.querySelectorAll<HTMLElement>(rootSelector)]
    if (scope instanceof HTMLElement && scope.matches(rootSelector))
        roots.unshift(scope)
    return roots
        .filter((root) => !controllers.has(root))
        .map(createImageCompare)
}

/** Bind one comparison. Pointer input starts only on its own handle. */
export function createImageCompare(root: HTMLElement): ImageCompareController {
    const existing = controllers.get(root)
    if (existing) return existing

    const ownedPart = <T extends HTMLElement>(selector: string) =>
        [...root.querySelectorAll<T>(selector)].find((part) => {
            const owner = part.closest(rootSelector)
            return !owner || owner === root || !root.contains(owner)
        })
    const input = ownedPart<HTMLInputElement>(
        '[data-slot="image-compare-input"]',
    )
    const handle = ownedPart<HTMLElement>('[data-slot="image-compare-handle"]')
    if (!input || !handle)
        throw new Error('ImageCompare requires an input and a handle.')

    let destroyed = false
    let pointerId: number | null = null
    let startX = 0
    let startValue = 50

    const updatePosition = () => {
        if (destroyed) return
        const parsed = Number(input.value)
        const value = Number.isFinite(parsed)
            ? Math.min(100, Math.max(0, parsed))
            : 50
        input.value = String(value)
        root.style.setProperty('--image-compare-position', `${value}%`)
    }

    const resetDrag = () => {
        const id = pointerId
        pointerId = null
        root.dataset.dragging = 'false'
        if (id !== null && handle.hasPointerCapture(id))
            handle.releasePointerCapture(id)
    }

    const startDrag = (event: PointerEvent) => {
        if (
            destroyed ||
            event.defaultPrevented ||
            event.button !== 0 ||
            !event.isPrimary ||
            pointerId !== null
        )
            return
        // Keep a click or a press off-center on the handle from moving the image.
        startX = event.clientX
        startValue = Number(input.value)
        pointerId = event.pointerId
        handle.setPointerCapture(pointerId)
        root.dataset.dragging = 'true'
        event.preventDefault()
        input.focus({ preventScroll: true })
    }

    const endDrag = (event: PointerEvent) => {
        if (event.pointerId === pointerId) resetDrag()
    }

    const moveDrag = (event: PointerEvent) => {
        if (
            destroyed ||
            event.pointerId !== pointerId ||
            root.clientWidth === 0
        )
            return
        const delta = ((event.clientX - startX) / root.clientWidth) * 100
        const value = Math.min(
            100,
            Math.max(0, Math.round((startValue + delta) * 100) / 100),
        )
        if (value === Number(input.value)) return
        input.value = String(value)
        input.dispatchEvent(new Event('input', { bubbles: true }))
    }

    const events = new AbortController()
    const { signal } = events
    input.addEventListener('input', updatePosition, { signal })
    handle.addEventListener('pointerdown', startDrag, { signal })
    handle.addEventListener('pointermove', moveDrag, { signal })
    handle.addEventListener('pointerup', endDrag, { signal })
    handle.addEventListener('pointercancel', endDrag, { signal })
    handle.addEventListener('lostpointercapture', endDrag, { signal })
    root.dataset.dragging = 'false'
    updatePosition()

    const controller: ImageCompareController = {
        updatePosition,
        startDrag,
        endDrag,
        moveDrag,
        destroy() {
            if (destroyed) return
            destroyed = true
            events.abort()
            resetDrag()
            controllers.delete(root)
        },
    }
    controllers.set(root, controller)
    return controller
}
```

#### src/components/ui/image-compare/index.ts

```ts
export { default as ImageCompareHandle } from './image-compare-handle.astro'
export { default as ImageCompareImage } from './image-compare-image.astro'
export { default as ImageCompare } from './image-compare.astro'

export type { ImageCompareImageProps, ImageCompareProps } from './types.ts'
```

#### src/components/ui/image-compare/types.ts

```ts
import type { ImageMetadata } from 'astro'

/**
 * Props for the comparison frame.
 * Div attributes such as `class` and `id` pass through.
 * Put both pictures and the handle in the default slot.
 */
export interface ImageCompareProps {
    /**
     * Divider position at first render, from 0 to 100.
     * `0` hides the clipped picture. `100` covers the frame with it.
     * @default 50
     */
    defaultValue?: number
    /**
     * Accessible name for the range control.
     * @default "Amount of the clipped image shown"
     */
    label?: string
}

/**
 * Props for one picture in a comparison.
 * Image attributes such as `class`, `width`, `height`, and `loading` pass through.
 */
export interface ImageCompareImageProps {
    /**
     * Picture file or address.
     */
    src: ImageMetadata | string
    /**
     * Text alternative for this picture.
     */
    alt: string
    /**
     * Show only the part of this picture to the left of the divider.
     * Set this on one picture. Leave it unset on the picture that fills the frame.
     * @default false
     */
    clip?: boolean
}
```

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

```astro
---
import {
  ImageCompareHandle,
  ImageCompareImage,
  ImageCompare,
} from "@/components/ui/image-compare"
---
```

```astro
<ImageCompare>
  <ImageCompareImage src={daylight} alt="Town in daylight" />
  <ImageCompareImage src={sunset} alt="Town at sunset" clip />
  <ImageCompareHandle />
</ImageCompare>
```

## Composition

Put the full picture first. Set `clip` on the picture that shows to the left of the divider. Place `ImageCompareHandle` after the pictures. Corner labels are normal elements in the same slot.

```text
ImageCompare
├── ImageCompareImage
├── ImageCompareImage clip
└── ImageCompareHandle
```

The handle slot replaces the grip icon. The divider does not take keyboard focus. The range control on `ImageCompare` does.

## API Reference

### ImageCompareProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/image-compare/types.ts"
    name="ImageCompareProps"
/>

Div attributes such as `class` and `id` pass through.

### ImageCompareImageProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/image-compare/types.ts"
    name="ImageCompareImageProps"
/>

Image attributes such as `class`, `width`, `height`, and `loading` pass through.

### ImageCompareHandle

`ImageCompareHandle` accepts div attributes such as `class`. Put a custom icon in its default slot.

Read the [installed source](/ui/r/image-compare.json) for the component source.

## When to use Image Compare

Use Image Compare for two pictures of the same subject. Drag the handle, or focus the control and use the arrow keys. Set `defaultValue` when the comparison should start away from the center.

## Keyboard and behavior

Tab reaches the range control. Arrow keys move the divider. Drag the handle to move it with a pointer. Clicking the pictures or pressing the handle without moving it does not change the position. The control name comes from `label`. Give each picture its own `alt` text.

## Theme and layout

The frame uses a 16:9 ratio. Pass another `aspect-*` class to change it. The divider and grip use the background color. Check both pictures in light and dark mode.
