← Components

Stacked card slider

Click to cycle cards with GSAP Flip.

Cards · FreeInstall ↓
Open preview ↗
Loading the demoNew tab ↗

Customize

300 px
0.67
20 px
5
0.50 s
6 px
Your code
<StackedCardSlider cards={cards} />

Changes show live and stay in the address, so a link keeps them.

Code

"use client";

import { useRef, useState } from "react";
import { gsap } from "gsap";
import { Flip } from "gsap/Flip";
import { useGSAP } from "@gsap/react";

// A deck of photos stacked on a diagonal. Click it (or press an arrow key, or swipe) and the front
// card slides away while the rest step forward and a fresh card settles in at the back.
// GSAP Flip does the stepping: React moves the cards to their new spots, Flip then plays the
// move backwards-to-forwards, so the animation always starts exactly where the cards were.

if (typeof window !== "undefined") gsap.registerPlugin(Flip);

export type StackedCard = {
  /** Image address. */
  image: string;
  /** What the photo shows, for screen readers. */
  alt?: string;
};

export type StackedCardSliderProps = {
  /** The cards, front card first. Each click brings the next one to the front. */
  cards: StackedCard[];
  /** Width of a card, in pixels. It shrinks on its own if the box is narrower. */
  cardWidth?: number;
  /** How far each card behind sticks out up and to the right, in pixels. */
  offsetStep?: number;
  /** Card width divided by card height. 0.67 is a 2:3 portrait. */
  aspectRatio?: number;
  /** How many cards show in the stack at once (the rest wait invisibly behind the last one). */
  visibleCards?: number;
  /** How long one step takes, in seconds. */
  duration?: number;
  /** The GSAP ease of the step, e.g. "sine.inOut" or "expo.inOut". */
  ease?: string;
  /** Corner radius of the cards, in pixels. */
  radius?: number;
  /** Called with the index (in `cards`) of the new front card as every step starts. */
  onChange?: (index: number) => void;
  /** Extra classes for the outer box. Give it a size (it fills its parent); the stack sits in the middle of it. */
  className?: string;
  /** Extra classes for each card image, e.g. a different shadow. */
  cardClassName?: string;
};

type View = {
  /** Which card is at the front */
  front: number;
  /** The card that is flying away right now, drawn as a copy on top of everything */
  leaving: number | null;
};

type Pending = {
  /** Where the cards were before the step */
  state: Flip.FlipState;
  /** +1 = forward, -1 = back */
  step: 1 | -1;
};

export function StackedCardSlider({
  cards,
  cardWidth = 300,
  offsetStep = 20,
  aspectRatio = 0.67,
  visibleCards = 5,
  duration = 0.5,
  ease = "sine.inOut",
  radius = 6,
  onChange,
  className = "",
  cardClassName = "",
}: StackedCardSliderProps) {
  const boxRef = useRef<HTMLDivElement>(null);
  const cardRefs = useRef<(HTMLImageElement | null)[]>([]);
  const leavingRef = useRef<HTMLImageElement>(null);
  const [view, setView] = useState<View>({ front: 0, leaving: null });
  // The step that was asked for and is waiting for React to move the cards
  const pending = useRef<Pending | null>(null);
  const busy = useRef(false);
  // Read when a step starts, so a new duration or ease needs no rebuild
  const settings = useRef({ duration, ease, onChange });
  settings.current = { duration, ease, onChange };
  const touchStart = useRef<{ x: number; y: number } | null>(null);
  const swiped = useRef(false);

  const count = cards.length;
  // If the list changes length, start again from the first card
  const front = count === 0 ? 0 : view.front % count;
  const shown = Math.max(1, Math.min(count, Math.round(visibleCards)));
  const total = offsetStep * (shown - 1);
  const cardHeight = `calc(var(--stack-card-width) / ${aspectRatio})`;

  const { contextSafe } = useGSAP(
    () => {
      busy.current = false;
      return () => {
        busy.current = false;
        pending.current = null;
      };
    },
    { scope: boxRef },
  );

  // Runs right after React has moved the cards to their new spots
  useGSAP(
    () => {
      const job = pending.current;
      if (!job) return;
      pending.current = null;

      const els = cardRefs.current.slice(0, count).filter((el): el is HTMLImageElement => el !== null);
      const { duration: time, ease: curve } = settings.current;
      const finish = () => {
        busy.current = false;
      };

      // The card flying away leaves toward the bottom left and fades out
      if (leavingRef.current) {
        gsap.to(leavingRef.current, {
          xPercent: -20,
          yPercent: 20,
          opacity: 0,
          transformOrigin: "bottom left",
          duration: time,
          ease: "expo.out",
          onComplete: () => setView((current) => ({ ...current, leaving: null })),
        });
      }

      Flip.from(job.state, {
        targets: els,
        // The cards never change size, so move them with transforms only
        scale: true,
        duration: time,
        ease: curve,
        // The one card that was not measured before the step is the one that arrives
        onEnter: (entering) =>
          gsap.from(entering, job.step === 1 ? { yPercent: 20, opacity: 0, duration: time, ease: "expo.out" } : { xPercent: -20, yPercent: 20, opacity: 0, transformOrigin: "bottom left", duration: time, ease: "expo.out" }),
        onComplete: finish,
        onInterrupt: finish,
      });
    },
    { scope: boxRef, dependencies: [view.front] },
  );

  const go = contextSafe((step: 1 | -1) => {
    if (busy.current || count < 2) return;
    const next = (front + step + count) % count;
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    settings.current.onChange?.(next);
    if (reduced) {
      setView({ front: next, leaving: null });
      return;
    }
    busy.current = true;
    const els = cardRefs.current.slice(0, count);
    // The card that arrives has no "before", so it is left out of the measurement
    const arriving = step === 1 ? front : next;
    const measured = els.filter((el, index): el is HTMLImageElement => el !== null && index !== arriving);
    pending.current = { state: Flip.getState(measured, { props: "opacity,filter" }), step };
    setView({ front: next, leaving: step === 1 ? front : null });
  });

  const onKeyDown = (event: React.KeyboardEvent) => {
    if (event.key === "ArrowRight" || event.key === "ArrowDown") {
      event.preventDefault();
      go(1);
    } else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
      event.preventDefault();
      go(-1);
    }
  };

  // A swipe goes forward (to the left) or back (to the right); a plain tap is a click
  const onPointerDown = (event: React.PointerEvent) => {
    touchStart.current = { x: event.clientX, y: event.clientY };
    swiped.current = false;
  };
  const onPointerUp = (event: React.PointerEvent) => {
    const start = touchStart.current;
    touchStart.current = null;
    if (!start) return;
    const dx = event.clientX - start.x;
    const dy = event.clientY - start.y;
    if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {
      swiped.current = true;
      go(dx < 0 ? 1 : -1);
    }
  };
  const onClick = (event: React.MouseEvent) => {
    if (swiped.current) {
      swiped.current = false;
      return;
    }
    go(event.shiftKey ? -1 : 1);
  };

  const spot = (rank: number) => {
    const slot = Math.min(rank, shown - 1);
    return { left: slot * offsetStep, top: total - slot * offsetStep };
  };

  const imageStyle = {
    width: "var(--stack-card-width)",
    height: cardHeight,
    borderRadius: radius,
  } as const;

  return (
    <div
      ref={boxRef}
      className={`flex h-full w-full items-center justify-center ${className}`}
      style={{
        // The card shrinks to fit the box both ways, so the whole stack always stays on screen
        containerType: "size",
        ["--stack-card-width" as string]: `min(${cardWidth}px, calc(100cqw - ${total + 32}px), calc((100cqh - ${total + 32}px) * ${aspectRatio}))`,
      }}
    >
      <button
        type="button"
        aria-label="Next card"
        onClick={onClick}
        onKeyDown={onKeyDown}
        onPointerDown={onPointerDown}
        onPointerUp={onPointerUp}
        onPointerCancel={() => (touchStart.current = null)}
        className="relative block shrink-0 cursor-pointer select-none rounded-[10px] border-0 bg-transparent p-0 outline-offset-[14px] focus-visible:outline-2 focus-visible:outline-current"
        style={{ width: `calc(var(--stack-card-width) + ${total}px)`, height: `calc(${cardHeight} + ${total}px)`, touchAction: "pan-y", WebkitTapHighlightColor: "transparent" }}
      >
        {cards.map((card, index) => {
          const rank = (index - front + count) % count;
          const visible = rank < shown;
          return (
            <img
              key={index}
              ref={(el) => {
                cardRefs.current[index] = el;
              }}
              src={card.image}
              alt={card.alt ?? `Card ${index + 1}`}
              aria-hidden={rank === 0 ? undefined : true}
              draggable={false}
              decoding="async"
              className={`pointer-events-none absolute block object-cover object-top shadow-[0_0_0_1px_rgba(0,0,0,0.18),0_22px_44px_-18px_rgba(0,0,0,0.55)] ${cardClassName}`}
              style={{
                ...imageStyle,
                ...spot(rank),
                zIndex: count - rank,
                opacity: visible ? 1 : 0,
                filter: `brightness(${1 - Math.min(rank, shown - 1) * 0.07})`,
                willChange: "transform, opacity",
              }}
            />
          );
        })}
        {view.leaving !== null && cards[view.leaving] ? (
          <img
            ref={leavingRef}
            src={cards[view.leaving]!.image}
            alt=""
            aria-hidden="true"
            draggable={false}
            className={`pointer-events-none absolute block object-cover object-top shadow-[0_0_0_1px_rgba(0,0,0,0.18),0_22px_44px_-18px_rgba(0,0,0,0.55)] ${cardClassName}`}
            style={{ ...imageStyle, ...spot(0), zIndex: count + 1, willChange: "transform, opacity" }}
          />
        ) : null}
      </button>
      <span className="sr-only" aria-live="polite">
        {cards[front] ? `${cards[front]!.alt ?? `Card ${front + 1}`}, card ${front + 1} of ${count}` : ""}
      </span>
    </div>
  );
}

The component. Installs to components/dimaac/stacked-card-slider.tsx.

Install

With the shadcn CLI

npx shadcn@latest add https://ui.dimaac.com/r/stacked-card-slider.json

It adds components/dimaac/stacked-card-slider.tsx and installs what it imports. With the @dimaac namespace in components.json (Docs) it's just npx shadcn@latest add @dimaac/stacked-card-slider.

By hand

npm install gsap @gsap/react
  1. Install the packages it uses: gsap, @gsap/react.
  2. Copy the component file below into components/dimaac/stacked-card-slider.tsx.
  3. It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
  4. Import it with import { StackedCardSlider } from "@/components/dimaac/stacked-card-slider" and give its parent a size: it fills it.

Props

PropTypeDefaultDescription
cards (required)StackedCard[]-The cards, front card first. Each click brings the next one to the front.
cardWidthnumber300Width of a card, in pixels. It shrinks on its own if the box is narrower.
offsetStepnumber20How far each card behind sticks out up and to the right, in pixels.
aspectRationumber0.67Card width divided by card height. 0.67 is a 2:3 portrait.
visibleCardsnumber5How many cards show in the stack at once (the rest wait invisibly behind the last one).
durationnumber0.5How long one step takes, in seconds.
easestring"sine.inOut"The GSAP ease of the step, e.g. "sine.inOut" or "expo.inOut".
radiusnumber6Corner radius of the cards, in pixels.
onChange(index: number) => void-Called with the index (in `cards`) of the new front card as every step starts.
classNamestring""Extra classes for the outer box. Give it a size (it fills its parent); the stack sits in the middle of it.
cardClassNamestring""Extra classes for each card image, e.g. a different shadow.

Use with AI

Agent prompt

Paste it into Claude Code, Cursor or any coding agent, or open it straight in a chat. It carries your Customize settings.

Prompt
Add the Stacked card slider component (<StackedCardSlider />) from DiMaac UI to this project.

Docs: https://ui.dimaac.com/components/stacked-card-slider
Source and dependencies (shadcn registry JSON): https://ui.dimaac.com/r/stacked-card-slider.json

Install it with:
npx shadcn@latest add https://ui.dimaac.com/r/stacked-card-slider.json

Then use it like this:
import { StackedCardSlider } from "@/components/dimaac/stacked-card-slider";
<StackedCardSlider cards={cards} />

If the shadcn CLI isn't set up here, fetch the registry JSON above, write files[0].content to components/dimaac/stacked-card-slider.tsx and install gsap, @gsap/react.
It uses Tailwind v4 classes, so make sure Tailwind scans that folder. Give its parent a size, keep light and dark mode working and keep its prefers-reduced-motion fallback.
Full index for agents: https://ui.dimaac.com/llms.txt

Files agents read

llms.txt
Every component and how to install it
stacked-card-slider.md
This page as Markdown: install, props and the full source
stacked-card-slider.json
The shadcn registry item

About

A stack of photo cards laid out on a diagonal. Click it, press an arrow key or swipe, and the front card slides away to the bottom left while the cards behind step forward and a new card settles in at the back. The stepping is done with GSAP Flip, so it always starts exactly where the cards were. It is a real button (Enter, Space and the arrow keys work, Shift-click goes back), announces the current card to screen readers, shrinks to fit narrow screens and swaps instantly when the visitor prefers reduced motion. Ported from the first DiMaac UI and rebuilt with useGSAP, full cleanup and a previous direction.

Installs to
components/dimaac/stacked-card-slider.tsx
Uses
gsap, @gsap/react
Tags
gsap, flip, cards, stack, slider, images

Portrait (lime blazer) by Amino on Lummi (Lummi License). Portrait (neon profile) by Shaun Duval on Lummi (Lummi License). Portrait (platinum blonde) by studiomiklus on Lummi (Lummi License). Portrait (red coat) by Lloyd Creates on Lummi (Lummi License). Portrait (tinted glasses) by SHIHO on Lummi (Lummi License). Fashion portrait (orange visor) by West Kast on Lummi (Lummi License). Portrait (face paint) by Steph Meade on Lummi (Lummi License).