Before and after slider
Drag the handle across a photo to compare before and after. Labels fade as the handle passes, and a short hint wiggle shows it can move.
"use client";
import {
useEffect,
useRef,
useState,
type CSSProperties,
type KeyboardEvent,
type PointerEvent as ReactPointerEvent,
} from "react";
import "./before-after.css";
type Side = { src: string; label: string; tone: string };
const BEFORE: Side = {
src: "/images/components-before-after-room-before-01.jpg",
label: "Before",
tone: "#8f8576",
};
const AFTER: Side = {
src: "/images/components-before-after-room-after-02.jpg",
label: "After",
tone: "#e0a77f",
};
function Img({ side, className }: { side: Side; className: string }) {
const img = useRef<HTMLImageElement>(null);
const [missing, setMissing] = useState(false);
useEffect(() => {
const el = img.current;
if (el && el.complete && el.naturalWidth === 0) setMissing(true);
}, []);
return (
<div className={className} style={{ "--tone": side.tone } as CSSProperties}>
{missing ? (
<span className="gu-ba__ph">{side.label} photo</span>
) : (
<img
ref={img}
src={side.src}
alt=""
draggable={false}
onError={() => setMissing(true)}
/>
)}
</div>
);
}
/**
* BeforeAfter
* - The "after" image is clipped with clip-path: inset(0 0 0 var(--x)), so nothing re-lays out while dragging.
* - The handle is a role="slider" (arrow keys move 5%, Home/End jump).
*/
export function BeforeAfter({ theme = "light" }: { theme?: "light" | "dark" }) {
const box = useRef<HTMLDivElement>(null);
const [x, setX] = useState(50);
const [active, setActive] = useState(false);
const [hinted, setHinted] = useState(false);
const fromEvent = (e: ReactPointerEvent<HTMLDivElement>) => {
const r = box.current!.getBoundingClientRect();
setX(Math.min(100, Math.max(0, ((e.clientX - r.left) / r.width) * 100)));
};
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
const map: Record<string, number> = {
ArrowLeft: x - 5,
ArrowRight: x + 5,
Home: 0,
End: 100,
};
if (!(e.key in map)) return;
e.preventDefault();
setX(Math.min(100, Math.max(0, map[e.key])));
setHinted(true);
};
return (
<figure className="gu-ba" data-theme={theme}>
<div
ref={box}
className="gu-ba__box"
style={{ "--x": `${x}%` } as CSSProperties}
data-active={active ? "" : undefined}
data-hint={hinted ? undefined : ""}
onPointerDown={(e) => {
e.currentTarget.setPointerCapture(e.pointerId);
setActive(true);
setHinted(true);
fromEvent(e);
}}
onPointerMove={(e) => active && fromEvent(e)}
onPointerUp={() => setActive(false)}
onPointerCancel={() => setActive(false)}
>
<Img side={BEFORE} className="gu-ba__img" />
<Img side={AFTER} className="gu-ba__img gu-ba__after" />
<span
className="gu-ba__tag gu-ba__tag--l"
style={{ opacity: x < 18 ? 0 : 1 }}
>
{BEFORE.label}
</span>
<span
className="gu-ba__tag gu-ba__tag--r"
style={{ opacity: x > 82 ? 0 : 1 }}
>
{AFTER.label}
</span>
<div
className="gu-ba__handle"
role="slider"
tabIndex={0}
aria-label="Compare before and after"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.round(x)}
aria-valuetext={`${Math.round(100 - x)}% after shown`}
onKeyDown={onKey}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="m9 7-5 5 5 5M15 7l5 5-5 5" />
</svg>
</div>
</div>
<figcaption>
Living room refresh: new plaster, oak floor and warm lighting.
</figcaption>
</figure>
);
}
Paste this into ChatGPT, Claude, Cursor, v0, Lovable or Bolt. It describes the layout, motion, colors and accessibility and includes the code, so the AI can rebuild it in any framework.
# Build this UI piece: Before and after slider
You are a senior front-end engineer. Recreate the piece below in my project. If I don't say which framework I use, ask once, then build it in that framework (React, Vue, Svelte, Angular, Astro, plain HTML/CSS/JS or anything else). Keep the behavior, motion, colors, spacing and accessibility exactly as described. Keep the code clean and commented for beginners.
## What it is
A before/after image comparison for an interior renovation. Drag anywhere on the photo (or use the arrow keys) to move a divider; the "after" photo is revealed on the right side. Labels fade near the edges and the handle wiggles once to hint it moves.
## Layout and look
- 760px max, 3:2, radius 24px. Two stacked photos; "Before" and "After" pills in the top corners (60% Ink, blur, Cream text).
- Divider: 3px Cream line with a soft shadow and a 52px Cream circle holding ‹ › arrows; while dragging it grows 12% and turns orange.
- Caption below in muted text.
## Behavior and motion
1. The after layer uses clip-path: inset(0 0 0 var(--x)); --x follows the pointer (pointer capture, clamp 0–100%).
2. touch-action: pan-y so vertical swipes still scroll the page.
3. Labels fade under 18% / over 82%.
4. Hint: 0.8s after load the handle swings -40px, +30px and back, once, until the user interacts.
## Images
Two photos of the same room from the same angle (3:2). Until they exist, two different tone blocks with "Before photo" / "After photo" text.
## Accessibility
- Handle is a role="slider" with value text "60% after shown"; Arrow keys ±5, Home/End.
- prefers-reduced-motion: no wiggle.
## Props
theme. Edit BEFORE, AFTER and the caption.
## Reference implementation
The original is written in React with one plain CSS file. Dependencies: none (plain React and CSS). Translate it faithfully; do not add new libraries unless my framework needs them.
### BeforeAfter.tsx
```tsx
"use client";
import {
useEffect,
useRef,
useState,
type CSSProperties,
type KeyboardEvent,
type PointerEvent as ReactPointerEvent,
} from "react";
import "./before-after.css";
type Side = { src: string; label: string; tone: string };
const BEFORE: Side = {
src: "/images/components-before-after-room-before-01.jpg",
label: "Before",
tone: "#8f8576",
};
const AFTER: Side = {
src: "/images/components-before-after-room-after-02.jpg",
label: "After",
tone: "#e0a77f",
};
function Img({ side, className }: { side: Side; className: string }) {
const img = useRef<HTMLImageElement>(null);
const [missing, setMissing] = useState(false);
useEffect(() => {
const el = img.current;
if (el && el.complete && el.naturalWidth === 0) setMissing(true);
}, []);
return (
<div className={className} style={{ "--tone": side.tone } as CSSProperties}>
{missing ? (
<span className="gu-ba__ph">{side.label} photo</span>
) : (
<img
ref={img}
src={side.src}
alt=""
draggable={false}
onError={() => setMissing(true)}
/>
)}
</div>
);
}
/**
* BeforeAfter
* - The "after" image is clipped with clip-path: inset(0 0 0 var(--x)), so nothing re-lays out while dragging.
* - The handle is a role="slider" (arrow keys move 5%, Home/End jump).
*/
export function BeforeAfter({ theme = "light" }: { theme?: "light" | "dark" }) {
const box = useRef<HTMLDivElement>(null);
const [x, setX] = useState(50);
const [active, setActive] = useState(false);
const [hinted, setHinted] = useState(false);
const fromEvent = (e: ReactPointerEvent<HTMLDivElement>) => {
const r = box.current!.getBoundingClientRect();
setX(Math.min(100, Math.max(0, ((e.clientX - r.left) / r.width) * 100)));
};
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
const map: Record<string, number> = {
ArrowLeft: x - 5,
ArrowRight: x + 5,
Home: 0,
End: 100,
};
if (!(e.key in map)) return;
e.preventDefault();
setX(Math.min(100, Math.max(0, map[e.key])));
setHinted(true);
};
return (
<figure className="gu-ba" data-theme={theme}>
<div
ref={box}
className="gu-ba__box"
style={{ "--x": `${x}%` } as CSSProperties}
data-active={active ? "" : undefined}
data-hint={hinted ? undefined : ""}
onPointerDown={(e) => {
e.currentTarget.setPointerCapture(e.pointerId);
setActive(true);
setHinted(true);
fromEvent(e);
}}
onPointerMove={(e) => active && fromEvent(e)}
onPointerUp={() => setActive(false)}
onPointerCancel={() => setActive(false)}
>
<Img side={BEFORE} className="gu-ba__img" />
<Img side={AFTER} className="gu-ba__img gu-ba__after" />
<span
className="gu-ba__tag gu-ba__tag--l"
style={{ opacity: x < 18 ? 0 : 1 }}
>
{BEFORE.label}
</span>
<span
className="gu-ba__tag gu-ba__tag--r"
style={{ opacity: x > 82 ? 0 : 1 }}
>
{AFTER.label}
</span>
<div
className="gu-ba__handle"
role="slider"
tabIndex={0}
aria-label="Compare before and after"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.round(x)}
aria-valuetext={`${Math.round(100 - x)}% after shown`}
onKeyDown={onKey}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="m9 7-5 5 5 5M15 7l5 5-5 5" />
</svg>
</div>
</div>
<figcaption>
Living room refresh: new plaster, oak floor and warm lighting.
</figcaption>
</figure>
);
}
```
### before-after.css
```css
/* BeforeAfter: change these colors to match your brand. */
.gu-ba {
--text: #0e0e10;
--muted: #57534b;
--handle: #f3eee3;
--handle-ink: #0e0e10;
--focus: #2b35ff;
width: min(100%, 760px);
margin: 0;
color: var(--text);
font-family: system-ui, sans-serif;
}
.gu-ba[data-theme="dark"] {
--text: #f3eee3;
--muted: #aea89c;
--focus: #d7ff3a;
}
.gu-ba__box {
position: relative;
aspect-ratio: 3 / 2;
overflow: hidden;
border-radius: 24px;
cursor: ew-resize;
touch-action: pan-y; /* horizontal drags go to us, vertical ones scroll the page */
user-select: none;
}
.gu-ba__img {
position: absolute;
inset: 0;
display: grid;
place-items: center;
background: var(--tone)
repeating-linear-gradient(
135deg,
rgb(255 255 255 / 0.12) 0 2px,
transparent 2px 18px
);
}
.gu-ba__img img {
width: 100%;
height: 100%;
object-fit: cover;
pointer-events: none;
}
.gu-ba__ph {
color: rgb(14 14 16 / 0.5);
font-size: clamp(1.4rem, 5vw, 2.6rem);
font-weight: 900;
letter-spacing: -0.04em;
}
.gu-ba__after {
clip-path: inset(0 0 0 var(--x));
}
.gu-ba__tag {
position: absolute;
top: 16px;
padding: 6px 12px;
border-radius: 999px;
background: rgb(14 14 16 / 0.6);
color: #f3eee3;
font-size: 0.8rem;
font-weight: 800;
backdrop-filter: blur(6px);
transition: opacity 0.25s;
pointer-events: none;
}
.gu-ba__tag--l {
left: 16px;
}
.gu-ba__tag--r {
right: 16px;
}
/* The divider line + round handle */
.gu-ba__handle {
position: absolute;
top: 0;
bottom: 0;
left: var(--x);
width: 0;
outline: none;
}
.gu-ba__handle::before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: -1.5px;
width: 3px;
background: var(--handle);
box-shadow: 0 0 12px rgb(0 0 0 / 0.3);
}
.gu-ba__handle svg {
position: absolute;
top: 50%;
left: 0;
width: 52px;
height: 52px;
padding: 13px;
border-radius: 50%;
background: var(--handle);
fill: none;
stroke: var(--handle-ink);
stroke-width: 2.2;
stroke-linecap: round;
stroke-linejoin: round;
box-shadow: 0 8px 24px -6px rgb(0 0 0 / 0.5);
translate: -50% -50%;
transition:
scale 0.25s cubic-bezier(0.34, 1.56, 0.64, 1),
background-color 0.2s;
}
.gu-ba__box[data-active] .gu-ba__handle svg {
scale: 1.12;
background: #ff5a1f;
}
.gu-ba__handle:focus-visible svg {
box-shadow:
0 0 0 4px var(--focus),
0 8px 24px -6px rgb(0 0 0 / 0.5);
}
/* A one-time wiggle hints that the handle moves */
.gu-ba__box[data-hint] .gu-ba__handle {
animation: gu-ba-hint 1.6s 0.8s cubic-bezier(0.45, 0, 0.55, 1);
}
@keyframes gu-ba-hint {
25% {
translate: -40px 0;
}
60% {
translate: 30px 0;
}
}
.gu-ba figcaption {
margin-top: 12px;
color: var(--muted);
font-size: 0.9rem;
}
@media (prefers-reduced-motion: reduce) {
.gu-ba__box[data-hint] .gu-ba__handle {
animation: none;
}
.gu-ba__handle svg,
.gu-ba__tag {
transition: none;
}
}
```
You might also want
Next piece: Big footer with signupLiquid glass controls
Components, advanced
Magazine cover ring 3D hero
Components, advanced, needs three
Snap carousel with progress
Components, intermediate

