Image Compare for Astro
Astro before-and-after pictures with a pointer and keyboard divider.
Installation
bunx --bun shadcn@latest add @gnostic/image-comparenpx shadcn@latest add @gnostic/image-comparepnpm dlx shadcn@latest add @gnostic/image-compareCopy the files
src/components/ui/image-compare/image-compare-handle.astrosrc/components/ui/image-compare/image-compare-image.astrosrc/components/ui/image-compare/image-compare.astrosrc/components/ui/image-compare/image-compare.tssrc/components/ui/image-compare/index.tssrc/components/ui/image-compare/types.ts
Usage
---
import {
ImageCompareHandle,
ImageCompareImage,
ImageCompare,
} from "@/components/ui/image-compare"
---
<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.
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
defaultValue?number
Divider position at first render, from 0 to 100. `0` hides the clipped picture. `100` covers the frame with it.
number50label?string
Accessible name for the range control.
string"Amount of the clipped image shown"Div attributes such as class and id pass through.
ImageCompareImageProps
srcImageMetadata | string
Picture file or address.
ImageMetadata | stringaltstring
Text alternative for this picture.
stringclip?boolean
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.
booleanfalseImage 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 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.

