Card stack animation: a swipeable deck with pointer events
Build a swipeable card stack animation: depth offsets, drag with rotation, throw-out past a threshold, spring back, plus buttons, arrow keys and React code.
A card stack shows one item at a time with the next few peeking out behind it. Drag the top card sideways and it tilts with your finger; let go past a certain point and it flies off while the rest of the deck moves up. It started with dating apps and is now common in onboarding flows, flashcards, product pickers and review queues.
The motion has three parts: the static depth of the stack, the live drag, and the release, which either throws the card out or springs it back. This guide builds all three with pointer events and CSS transitions, adds buttons and arrow keys so it works without a pointer, and ends with a React version.
How the animation is put together
| Part | Property | Duration | Delay | Easing |
|---|---|---|---|---|
| Stack depth | translateY(i × 14px) scale(1 − i × .06) | static | 0 | none |
| Drag | translateX(dx) rotate(dx × .08deg) | follows the pointer | 0 | none |
| Throw out | transform to ±150% and ±24deg, opacity to 0 | 320 ms | 0 | cubic-bezier(.2, .7, .3, 1) |
| Spring back | transform to the stack position | 450 ms | 0 | cubic-bezier(.34, 1.56, .64, 1) |
| Next cards move up | transform, opacity | 450 ms / 300 ms | 0 | cubic-bezier(.34, 1.56, .64, 1) / ease |
Every card gets its place from a single index, --i. Index 0 is the top card, 1 sits slightly lower and smaller, 2 lower again. Cards from index 3 down are invisible and wait their turn. When the top card leaves, every other card's index drops by one and the CSS transition moves it into its new slot, which is the "deck moves up" effect for free.
The HTML
<div class="cs-stack" tabindex="0" role="group"
aria-label="Card stack. Use the left and right arrow keys to swipe the top card.">
<article class="cs-card" data-title="Aurora">…</article>
<article class="cs-card" data-title="Lagoon">…</article>
<article class="cs-card" data-title="Violet">…</article>
<article class="cs-card" data-title="Moss">…</article>
</div>
<div class="cs-buttons">
<button type="button" data-dir="-1">Skip left</button>
<button type="button" data-dir="1">Skip right</button>
</div>
<p class="cs-live" aria-live="polite"></p>
The stack is focusable so arrow keys work on it, and the buttons do the same thing for people who prefer to tab and press. The visually hidden live region announces the new top card after each swipe.
The CSS
.cs-stack { position: relative; width: 220px; height: 280px; }
.cs-card {
--i: 0;
position: absolute; inset: 0;
border-radius: 20px;
z-index: calc(10 - var(--i));
opacity: calc(1 - var(--i) * .25);
transform: translateY(calc(var(--i) * 14px)) scale(calc(1 - var(--i) * .06));
transition: transform .45s cubic-bezier(.34, 1.56, .64, 1), opacity .3s ease;
touch-action: pan-y; /* vertical scroll still works on touch */
user-select: none;
cursor: grab;
}
.cs-card.cs-hidden { opacity: 0; }
/* while dragging, follow the pointer with no lag */
.cs-card.is-dragging { transition: none; cursor: grabbing; }
/* the throw: fast start, soft finish, above the rest of the deck */
.cs-card.is-leaving {
z-index: 20;
transition: transform .32s cubic-bezier(.2, .7, .3, 1), opacity .32s ease;
}
/* used for one frame to move a thrown card to the back without animating */
.cs-card.is-reset { transition: none; }
@media (prefers-reduced-motion: reduce) {
.cs-card, .cs-card.is-leaving { transition: opacity .15s linear; }
}
The default transition uses an overshooting curve. It does two jobs: when a released card springs back, it slightly passes its resting point and settles, and when the deck moves up, each card lands with a small bounce. The throw uses its own curve with no overshoot, because a card leaving the screen should not wobble on the way out. If you want to understand the shape of these curves, the easing functions guide walks through them.
The JavaScript
The script tracks one drag at a time with pointer events, which cover mouse, touch and pen with the same code.
const stack = document.querySelector('.cs-stack');
const live = document.querySelector('.cs-live');
let cards = [...stack.querySelectorAll('.cs-card')];
const reduce = matchMedia('(prefers-reduced-motion: reduce)');
let busy = false, drag = null;
function layout() {
cards.forEach((c, i) => {
c.style.setProperty('--i', i);
c.classList.toggle('cs-hidden', i > 2);
c.setAttribute('aria-hidden', String(i !== 0));
});
}
function dismiss(dir) {
if (busy) return;
busy = true;
const c = cards[0];
c.classList.remove('is-dragging');
c.classList.add('is-leaving');
c.style.transform = `translateX(${dir * 150}%) rotate(${dir * 24}deg)`;
c.style.opacity = '0';
cards.push(cards.shift()); // the deck moves up right away
layout();
live.textContent = 'Top card: ' + cards[0].dataset.title;
setTimeout(() => {
c.classList.add('is-reset'); // jump to the back without a transition
c.classList.remove('is-leaving');
c.style.transform = '';
c.style.opacity = '';
void c.offsetWidth; // force a style flush
c.classList.remove('is-reset');
busy = false;
}, reduce.matches ? 160 : 320);
}
stack.addEventListener('pointerdown', e => {
const c = e.target.closest('.cs-card');
if (busy || c !== cards[0] || e.button > 0) return;
c.setPointerCapture(e.pointerId);
c.classList.add('is-dragging');
drag = { card: c, x0: e.clientX, dx: 0, lastX: e.clientX, lastT: e.timeStamp, v: 0 };
});
stack.addEventListener('pointermove', e => {
if (!drag) return;
drag.dx = e.clientX - drag.x0;
const dt = e.timeStamp - drag.lastT;
if (dt > 0) drag.v = (e.clientX - drag.lastX) / dt; // px per ms
drag.lastX = e.clientX; drag.lastT = e.timeStamp;
const r = Math.max(-18, Math.min(18, drag.dx * 0.08));
drag.card.style.transform = `translateX(${drag.dx}px) rotate(${r}deg)`;
});
function release() {
if (!drag) return;
const d = drag; drag = null;
const far = Math.abs(d.dx) > 110;
const flick = Math.abs(d.v) > 0.6 && Math.abs(d.dx) > 30;
if (far || flick) dismiss(d.dx > 0 ? 1 : -1);
else {
d.card.classList.remove('is-dragging');
d.card.style.transform = ''; // CSS transition springs it back
}
}
stack.addEventListener('pointerup', release);
stack.addEventListener('pointercancel', release);
stack.addEventListener('keydown', e => {
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
e.preventDefault();
dismiss(e.key === 'ArrowRight' ? 1 : -1);
});
document.querySelectorAll('.cs-buttons button').forEach(b =>
b.addEventListener('click', () => dismiss(Number(b.dataset.dir))));
layout();
A few details matter more than they look:
setPointerCapturekeeps sending move events to the card even when the pointer leaves it, so a fast drag does not drop the card halfway.- Rotation is tied to distance and clamped. 0.08 degrees per pixel gives about 9 degrees at the threshold, which feels like a card held at the bottom. The clamp at 18 degrees stops long drags from spinning it sideways.
- Distance or flick. A slow drag must pass 110px. A quick flick of more than 0.6px per millisecond counts even if it is short, which is what people expect on touch.
- The deck moves up during the throw, not after it. Reordering at the start makes the two motions overlap, so the stack never looks empty.
- The demo loops by sending each thrown card to the back. In a real product you would usually remove it and call a handler with the direction.
The React version
The same logic in React, without any animation library. This version removes each card and calls onSwipe, which is how a real review queue or picker behaves. It uses the CSS above.
import { useRef, useState } from 'react';
const THRESHOLD = 110;
export function CardStack({ items, onSwipe }) {
const [cards, setCards] = useState(items);
const [dx, setDx] = useState(0);
const [dragging, setDragging] = useState(false);
const [leaving, setLeaving] = useState(0); // -1 left, 1 right, 0 none
const drag = useRef({ x0: 0, lastX: 0, lastT: 0, v: 0 });
const reduce = typeof window !== 'undefined' &&
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
function dismiss(dir) {
if (leaving || cards.length === 0) return;
setLeaving(dir);
setTimeout(() => {
onSwipe?.(cards[0], dir > 0 ? 'right' : 'left');
setCards(c => c.slice(1));
setLeaving(0);
setDx(0);
}, reduce ? 160 : 320);
}
function onPointerDown(e) {
if (leaving || e.button > 0) return;
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = { x0: e.clientX, lastX: e.clientX, lastT: e.timeStamp, v: 0 };
setDragging(true);
}
function onPointerMove(e) {
if (!dragging) return;
const d = drag.current, dt = e.timeStamp - d.lastT;
if (dt > 0) d.v = (e.clientX - d.lastX) / dt;
d.lastX = e.clientX; d.lastT = e.timeStamp;
setDx(e.clientX - d.x0);
}
function onPointerUp() {
if (!dragging) return;
setDragging(false);
const flick = Math.abs(drag.current.v) > 0.6 && Math.abs(dx) > 30;
if (Math.abs(dx) > THRESHOLD || flick) dismiss(dx > 0 ? 1 : -1);
else setDx(0);
}
function onKeyDown(e) {
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
e.preventDefault();
dismiss(e.key === 'ArrowRight' ? 1 : -1);
}
return (
<div className="cs">
<div className="cs-stack" tabIndex={0} role="group" onKeyDown={onKeyDown}
aria-label="Card stack. Use the left and right arrow keys to swipe the top card.">
{cards.slice(0, 4).map((card, i) => {
const top = i === 0;
const style = { '--i': i };
let className = 'cs-card' + (i > 2 ? ' cs-hidden' : '');
if (top && leaving) {
style.transform = `translateX(${leaving * 150}%) rotate(${leaving * 24}deg)`;
style.opacity = 0;
className += ' is-leaving';
} else if (top && (dragging || dx)) {
const r = Math.max(-18, Math.min(18, dx * 0.08));
style.transform = `translateX(${dx}px) rotate(${r}deg)`;
if (dragging) className += ' is-dragging';
}
return (
<article key={card.id} className={className} style={style} aria-hidden={!top}
{...(top && { onPointerDown, onPointerMove,
onPointerUp, onPointerCancel: onPointerUp })}>
{card.content}
</article>
);
})}
</div>
<div className="cs-buttons">
<button type="button" onClick={() => dismiss(-1)}>Skip left</button>
<button type="button" onClick={() => dismiss(1)}>Skip right</button>
</div>
<p className="cs-live" aria-live="polite">
{cards[0] ? `Top card: ${cards[0].title}` : 'No cards left'}
</p>
</div>
);
}
When the top card is removed, the next card re-renders with --i: 0, and the CSS transition carries it up into place. Because each card is keyed by its id, React reuses the same DOM node, which is what lets the transition run.
With Framer Motion
If the project already uses Framer Motion, its drag="x" prop replaces the pointer handling. Map the drag offset to rotation with useMotionValue and useTransform, then in onDragEnd check info.offset.x and info.velocity.x against your thresholds. Throw the card by animating x off-screen, or let dragSnapToOrigin spring it back. Wrap the list in AnimatePresence and give the leaving card an exit animation so it can finish after it is removed. The keyframes to Framer Motion guide shows how to translate the curves above into Framer Motion transitions.
Timing that feels right
- Depth offset: 10 to 16px per card, scale step .04 to .07. Less and the cards behind are hard to see; more and the stack looks like a staircase. Show two cards behind the top one at most.
- Throw: 250 to 350 ms with a fast start. The card is already moving when the user lets go, so the curve should start steep and continue that momentum. A slow ease-in at release feels like the card stopped and then decided to leave.
- Spring back: 400 to 500 ms with a small overshoot. A
cubic-bezier()with a second value above 1 gives one gentle overshoot. Keep it to a few percent, or the card looks like it is made of rubber. - Rotation: 6 to 12 degrees at the threshold. Rotation is what makes it feel like a physical card. Too much and it reads as a spin rather than a tilt.
- Button and key swipes: same throw as a drag. Reusing one function means every input method produces the same motion, which keeps the component predictable.
Accessibility notes
- Never make dragging the only way. WCAG 2.5.7 asks for a single-pointer alternative to dragging, and the buttons provide it. Arrow keys cover keyboard users.
- Label what the directions mean. "Skip left" is fine for a demo; in a product use the real action, like "Not interested" and "Save".
- Hide the cards behind the top one from assistive technology with
aria-hidden, and announce the new top card in a polite live region. - Under
prefers-reduced-motion: reducethe cards cross-fade instead of flying and bouncing. The drag still follows the pointer, because direct manipulation that the user controls is not the kind of motion that causes problems. More on this in the reduced motion guide.
Match a stack you have seen
Card stacks differ in small ways that change the feel: the depth offset, how much the card rotates, how long the throw takes, whether the next card scales up with a bounce. To match one from a live site, start recording with the Capture Motion extension, swipe the card, and it reads the keyframes, duration, delay and easing of every card that moved, whether the stack runs on CSS transitions, the Web Animations API or GSAP. You get CSS, React, GSAP or JSON, and the JSON pastes into the Figma plugin as a Figma Motion timeline.
Questions
How far should the user drag before the card is thrown out?
Around 100 to 120 pixels, or about 30 percent of the card width on small cards. Also throw on a fast flick even if the distance is short, because that is how people expect a swipe to work on touch screens.
Why does my page scroll while I drag the card on a phone?
The browser treats the touch as a scroll before your pointer events can claim it. Set touch-action: pan-y on the card so vertical scrolling still works but horizontal drags go to your code.
Is a swipe-only card stack accessible?
No. Dragging is not possible for many keyboard, switch and screen reader users. Add visible buttons for each direction, arrow key support on the focused stack, and a live region that announces the new top card.
Can I copy a card stack animation from another site?
Yes. Trigger the swipe while the Capture Motion Chrome extension is recording and it reads the keyframes, durations, delays and easing of each card, including GSAP-driven stacks, then exports CSS, React, GSAP or JSON.
