Image Compare Slider
A before/after comparison slider whose divider chases the cursor on a spring and eases back to rest on leave. Touch drags the handle with pointer capture, arrow keys nudge it through a real slider role, and the reveal is a clip-path so both images stay full-bleed. Corner labels and orientation are props.
SliderReactMotionTailwind CSSSolar Icons
CSSTailwind
Manual
Create a file and paste the following code into it.
image-compare-slider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"use client";
import {
useRef,
useState,
type CSSProperties,
type KeyboardEvent,
type PointerEvent,
} from "react";
import {
motion,
useMotionValue,
useSpring,
useTransform,
type SpringOptions,
} from "motion/react";
import { AltArrowLeft as CaretLeft, AltArrowRight as CaretRight } from "@solar-icons/react";
import { cn } from "@/lib/cn";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface ImageCompareSliderProps {
/** Source URL for the "before" image (left, or top when vertical). [Required] */
beforeImage: string;
/** Source URL for the "after" image (right, or bottom when vertical). [Required] */
afterImage: string;
/** Alt text for the before image. [Optional, default: "Before"] */
beforeAlt?: string;
/** Alt text for the after image. [Optional, default: "After"] */
afterAlt?: string;
/** Corner labels rendered over each side. [Optional] */
beforeLabel?: string;
afterLabel?: string;
/** Divider direction. [Optional, default: "horizontal"] */
orientation?: "horizontal" | "vertical";
/** Divider rest position as a percentage, 0 to 100. [Optional, default: 50] */
initialPosition?: number;
/** CSS color of the divider line and handle. [Optional, default: "white"] */
dividerColor?: string;
/** Divider line thickness in px. [Optional, default: 2] */
dividerWidth?: number;
/** Diameter of the grab handle in px. [Optional, default: 40] */
handleSize?: number;
/** Spring for the divider follow. [Optional, default: stiffness 300, damping 30] */
springOptions?: SpringOptions;
className?: string;
}
/* ------------------------------------------------------------------ */
/* ImageCompareSlider */
/* ------------------------------------------------------------------ */
/**
* A before/after image comparison slider. On desktop the divider follows
* the cursor with a spring and eases back to rest on leave; on touch the
* handle drags with pointer capture; the handle is also a real slider for
* the keyboard (arrow keys nudge, Home/End jump). The reveal is a
* clip-path, so both images stay full-bleed and never reflow.
* @param {string} beforeImage - Before image URL [Required]
* @param {string} afterImage - After image URL [Required]
* @param {string} orientation - "horizontal" or "vertical" [Optional, default: "horizontal"]
* @param {number} initialPosition - Rest position 0 to 100 [Optional, default: 50]
*/
export function ImageCompareSlider({
beforeImage,
afterImage,
beforeAlt = "Before",
afterAlt = "After",
beforeLabel,
afterLabel,
orientation = "horizontal",
initialPosition = 50,
dividerColor = "white",
dividerWidth = 2,
handleSize = 40,
springOptions = { stiffness: 300, damping: 30 },
className,
}: ImageCompareSliderProps) {
const ref = useRef<HTMLDivElement>(null);
const dragging = useRef(false);
const isHorizontal = orientation === "horizontal";
// Announced slider value — updated on the discrete interactions
// (keys, drag end) instead of every spring frame.
const [announced, setAnnounced] = useState(Math.round(initialPosition));
const raw = useMotionValue(initialPosition);
const position = useSpring(raw, springOptions);
const clipPath = useTransform(position, (v) =>
isHorizontal ? `inset(0 ${100 - v}% 0 0)` : `inset(0 0 ${100 - v}% 0)`,
);
const dividerPos = useTransform(position, (v) => `${v}%`);
const setFromClientPoint = (clientX: number, clientY: number) => {
const el = ref.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const pct = isHorizontal
? ((clientX - rect.left) / rect.width) * 100
: ((clientY - rect.top) / rect.height) * 100;
raw.set(Math.max(0, Math.min(100, pct)));
};
const handlePointerMove = (e: PointerEvent<HTMLDivElement>) => {
// Mouse hovers freely; touch/pen only steer while dragging the handle.
if (e.pointerType !== "mouse" && !dragging.current) return;
setFromClientPoint(e.clientX, e.clientY);
};
const handlePointerLeave = () => {
if (!dragging.current) raw.set(initialPosition);
};
const startDrag = (e: PointerEvent<HTMLButtonElement>) => {
dragging.current = true;
e.currentTarget.setPointerCapture(e.pointerId);
};
const endDrag = () => {
dragging.current = false;
setAnnounced(Math.round(raw.get()));
};
const handleKeyDown = (e: KeyboardEvent<HTMLButtonElement>) => {
const step = e.shiftKey ? 10 : 3;
let next: number | null = null;
if (e.key === "ArrowLeft" || e.key === "ArrowDown") next = raw.get() - step;
if (e.key === "ArrowRight" || e.key === "ArrowUp") next = raw.get() + step;
if (e.key === "Home") next = 0;
if (e.key === "End") next = 100;
if (next === null) return;
e.preventDefault();
const clamped = Math.max(0, Math.min(100, next));
raw.set(clamped);
setAnnounced(Math.round(clamped));
};
const labelClass = cn(
"pointer-events-none absolute z-10 rounded-full bg-black/55 px-2.5 py-1",
"text-[11px] font-medium uppercase tracking-wider text-white backdrop-blur-sm",
);
return (
<div
ref={ref}
className={cn(
"relative select-none overflow-hidden",
isHorizontal ? "cursor-col-resize" : "cursor-row-resize",
className,
)}
onPointerMove={handlePointerMove}
onPointerLeave={handlePointerLeave}
>
{/* After image (in flow — gives the container its intrinsic size) */}
<img
src={afterImage}
alt={afterAlt}
draggable={false}
className="block h-full w-full object-cover"
/>
{/* Before image (clipped top layer) */}
<motion.div className="absolute inset-0" style={{ clipPath }}>
<img
src={beforeImage}
alt={beforeAlt}
draggable={false}
className="block h-full w-full object-cover"
/>
</motion.div>
{beforeLabel && (
<span className={cn(labelClass, "left-3 top-3")}>{beforeLabel}</span>
)}
{afterLabel && (
<span className={cn(labelClass, "right-3 top-3")}>{afterLabel}</span>
)}
{/* Divider + handle */}
<motion.div
className="absolute z-20"
style={
{
[isHorizontal ? "left" : "top"]: dividerPos,
[isHorizontal ? "x" : "y"]: "-50%",
...(isHorizontal
? { top: 0, bottom: 0, width: dividerWidth }
: { left: 0, right: 0, height: dividerWidth }),
backgroundColor: dividerColor,
boxShadow: "0 0 12px rgba(0,0,0,0.35)",
} as CSSProperties
}
>
<button
type="button"
role="slider"
aria-label="Comparison position"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={announced}
aria-orientation={orientation}
onKeyDown={handleKeyDown}
onPointerDown={startDrag}
onPointerUp={endDrag}
onPointerCancel={endDrag}
className={cn(
"absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 touch-none font-medium",
"flex items-center justify-center rounded-full text-zinc-700",
"shadow-[0_2px_12px_rgba(0,0,0,0.35)] outline-none",
"focus-visible:ring-2 focus-visible:ring-sky-500 focus-visible:ring-offset-2",
"active:scale-[0.96] transition-transform",
)}
style={{
width: handleSize,
height: handleSize,
backgroundColor: dividerColor,
rotate: isHorizontal ? undefined : "90deg",
}}
>
<CaretLeft weight="Bold" className="h-3.5 w-3.5" />
<CaretRight weight="Bold" className="h-3.5 w-3.5" />
</button>
</motion.div>
</div>
);
}
Update the import paths to match your project setup.
Similar components
Install via CLI
Resource details
PublishedJuly 16, 2026
CategorySlider
ReactMotionTailwind CSSSolar Icons
Install via CLI
Resource details
PublishedJuly 16, 2026
CategorySlider
ReactMotionTailwind CSSSolar Icons