---
title: Stacked card slider
description: Click to cycle cards with GSAP Flip.
category: Cards
tier: free
url: https://ui.dimaac.com/components/stacked-card-slider
registry: https://ui.dimaac.com/r/stacked-card-slider.json
---

# Stacked card slider

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.

## Install

With the shadcn CLI:

```bash
npx shadcn@latest add https://ui.dimaac.com/r/stacked-card-slider.json
pnpm dlx shadcn@latest add https://ui.dimaac.com/r/stacked-card-slider.json
bunx --bun shadcn@latest add https://ui.dimaac.com/r/stacked-card-slider.json
```

With the `@dimaac` namespace in components.json: `npx shadcn@latest add @dimaac/stacked-card-slider`

Dependencies:

```bash
pnpm add gsap @gsap/react
npm install gsap @gsap/react
```

By hand:

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.

## Usage

```tsx
import { StackedCardSlider } from "@/components/dimaac/stacked-card-slider";

<StackedCardSlider cards={cards} />
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `cards` (required) | `StackedCard[]` | - | The cards, front card first. Each click brings the next one to the front. |
| `cardWidth` | `number` | `300` | Width of a card, in pixels. It shrinks on its own if the box is narrower. |
| `offsetStep` | `number` | `20` | How far each card behind sticks out up and to the right, in pixels. |
| `aspectRatio` | `number` | `0.67` | Card width divided by card height. 0.67 is a 2:3 portrait. |
| `visibleCards` | `number` | `5` | How many cards show in the stack at once (the rest wait invisibly behind the last one). |
| `duration` | `number` | `0.5` | How long one step takes, in seconds. |
| `ease` | `string` | `"sine.inOut"` | The GSAP ease of the step, e.g. "sine.inOut" or "expo.inOut". |
| `radius` | `number` | `6` | Corner 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. |
| `className` | `string` | `""` | Extra classes for the outer box. Give it a size (it fills its parent); the stack sits in the middle of it. |
| `cardClassName` | `string` | `""` | Extra classes for each card image, e.g. a different shadow. |

## Credits

- Portrait (lime blazer): Amino, Lummi (https://www.lummi.ai/photo/vivid-portrait-on-pink-oxbow), Lummi License
- Portrait (neon profile): Shaun Duval, Lummi (https://www.lummi.ai/photo/portrait-with-neon-sunglasses-gindg), Lummi License
- Portrait (platinum blonde): studiomiklus, Lummi (https://www.lummi.ai/photo/striking-portrait-jodiu), Lummi License
- Portrait (red coat): Lloyd Creates, Lummi (https://www.lummi.ai/photo/poised-portrait-ooi9b), Lummi License
- Portrait (tinted glasses): SHIHO, Lummi (https://www.lummi.ai/photo/vibrant-woman-portrait-htofy), Lummi License
- Fashion portrait (orange visor): West Kast, Lummi (https://www.lummi.ai/photo/fashion-portrait-with-orange-visor-damql), Lummi License
- Portrait (face paint): Steph Meade, Lummi (https://www.lummi.ai/photo/expressive-minimal-portrait-jrfyc), Lummi License

## Source

### stacked-card-slider.tsx → `components/dimaac/stacked-card-slider.tsx`

```tsx
"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>
  );
}
```

### demo.tsx (the demo on the page, not installed)

```tsx
"use client";

import { useRef, useState } from "react";
import { gsap } from "gsap";
import { useGSAP } from "@gsap/react";
import { StackedCardSlider, type StackedCard, type StackedCardSliderProps } from "@/components/dimaac/stacked-card-slider";

// Seven portraits from Lummi (Lummi License: free for personal and commercial use).
// The big name on the left follows whichever card is at the front.

const portraits: (StackedCard & { name: string })[] = [
  { name: "Lime", image: "https://ui.dimaac.com/media/portraits/lime-blazer-4x5.jpg", alt: "A person with curly red hair in a lime green blazer against a bright pink background" },
  { name: "Neon", image: "https://ui.dimaac.com/media/portraits/neon-profile-4x5.jpg", alt: "A profile portrait of a woman in neon pink sunglasses against a vibrant blue background" },
  { name: "Platinum", image: "https://ui.dimaac.com/media/portraits/platinum-blonde-4x5.jpg", alt: "A young man with platinum blonde hair and a yellow jacket against a bold orange background" },
  { name: "Scarlet", image: "https://ui.dimaac.com/media/portraits/red-coat-4x5.jpg", alt: "A person in a red coat against a deep blue background" },
  { name: "Dusk", image: "https://ui.dimaac.com/media/portraits/tinted-glasses-4x5.jpg", alt: "A woman in purple-tinted sunglasses and braided hair against a glowing orange background" },
  { name: "Visor", image: "https://ui.dimaac.com/media/fashion/orange-visor-4x5.jpg", alt: "A woman in an orange visor and navy dress with red lips against a teal background" },
  { name: "Noir", image: "https://ui.dimaac.com/media/portraits/glossy-lowkey-4x5.jpg", alt: "A close-up portrait of a woman with glossy lips and sparkling earrings in dramatic black and white light, with a flash of purple at the collar" },
];

const two = (n: number) => String(n).padStart(2, "0");

export default function Demo(props: Partial<StackedCardSliderProps>) {
  const [index, setIndex] = useState(0);
  const labelRef = useRef<HTMLDivElement>(null);

  // The name and number rise in again every time the front card changes
  useGSAP(
    () => {
      if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
      gsap.from("[data-swap]", { yPercent: 40, opacity: 0, duration: 0.7, ease: "expo.out", stagger: 0.06 });
    },
    { scope: labelRef, dependencies: [index] },
  );

  return (
    <div className="relative h-full w-full overflow-hidden bg-[#ebe8e1] text-[#17171a] dark:bg-[#121214] dark:text-[#ecebe6]" style={{ fontFamily: '"DM Sans", system-ui, sans-serif' }}>
      <div aria-hidden="true" className="pointer-events-none absolute top-1/2 left-1/2 size-[70vmin] -translate-x-1/2 -translate-y-1/2 rounded-full bg-[#d4cfc4] blur-[90px] dark:bg-[#26262c]" />

      <StackedCardSlider cards={portraits} {...props} onChange={setIndex} className={`absolute inset-0 z-10 pt-8 pb-28 md:py-10 ${props.className ?? ""}`} />

      <div ref={labelRef} className="pointer-events-none absolute right-6 bottom-20 left-6 z-20 text-center md:right-auto md:bottom-14 md:left-12 md:text-left" aria-hidden="true">
        <div className="overflow-hidden">
          <p data-swap className="font-mono text-[12px] tracking-wide uppercase opacity-60">
            {two(index + 1)} / {two(portraits.length)}
          </p>
        </div>
        <div className="overflow-hidden pb-2">
          <h2 data-swap className="text-[clamp(44px,8vw,112px)] leading-[0.95] font-medium tracking-[-0.045em]">
            {portraits[index]?.name}
          </h2>
        </div>
      </div>

      <footer className="pointer-events-none absolute inset-x-6 bottom-6 z-20 flex justify-between font-mono text-[11px] tracking-wide uppercase opacity-70">
        <span className="mx-auto">Click · swipe · arrow keys</span>
      </footer>
    </div>
  );
}
```

## Agent prompt

```text
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
```
