← All items

Sticky card stack

effect · scroll · card · T1 · v1.0.0 · ready

About

A list of equal-height cards. Scrolling, each card sticks slightly below the previous one, so the stacked cards' top edges peek out; the card being covered scales down from its top edge and darkens, in step with the scroll.

Layers

Native
Scroll-driven animations, Registered custom properties
JS
Browsers without animation-timeline: view() (scroll-progress primitive).
Static
Cards still stick and stack; nothing scales or dims.

Browser support (native layer)

  • Scroll-driven animations: Baseline low · chrome 115, chrome_android 115, edge 115, firefox 159, firefox_android 159, safari 26, safari_ios 26 · Firefox reportedly needs a non-zero animation-duration.
  • Registered custom properties: Baseline low · chrome 85, chrome_android 85, edge 85, firefox 128, firefox_android 128, safari 16.4, safari_ios 16.4

Samsung Internet: Chromium-based; not tracked by web-features.

Skin

VariableDefaultMeaning
--sticky-card-stack-top1remDistance between the viewport top and the first stuck card.
--sticky-card-stack-peek0.75remHow far each card sticks below the previous one: the visible strip of covered cards.
--sticky-card-stack-scale0.92Scale of a fully covered card.
--sticky-card-stack-dim0.35How much a fully covered card darkens (0 = not at all, 1 = black).

Accessibility

Static layer: cards still stack, without scaling or dimming.

Ordered list; reading order equals visual order. Keyboard focus inside a covered card raises that card above the stack, unscaled and undimmed.

Sources

  • reel · thedesignshop.tds · "Staggered Scroll" reel; technique only (P6).

Code

Download zip

Self-contained: copy every file, keeping the folder structure.

mechanism.module.css
/* web-effects sticky-card-stack 1.0.0 · MIT-0 */
/* Mechanism of the sticky card stack (D2.8, D3.11), shared by both styling variants.
   Driver / renderer split (D2.7): the stack's progress through its `exit-crossing` view range
   (0–1) lives in --_sticky-card-stack-progress. L1: a native view() timeline animates it.
   L2: the scroll-progress driver writes it inline (data-layer="js"). L3: it stays 0 and no
   transform applies. Each card derives its own share from its index (set inline). */
@property --_sticky-card-stack-progress {
  syntax: "<number>";
  inherits: true;
  initial-value: 0;
}

.stack {
  --_sticky-card-stack-top: var(--sticky-card-stack-top, 1rem);
  --_sticky-card-stack-peek: var(--sticky-card-stack-peek, 0.75rem);
  --_sticky-card-stack-scale: var(--sticky-card-stack-scale, 0.92);
  --_sticky-card-stack-dim: var(--sticky-card-stack-dim, 0.35);
  margin: 0;
  padding: 0;
  list-style: none;
}

.card {
  position: sticky;
  top: calc(
    var(--_sticky-card-stack-top) + var(--_sticky-card-stack-index) *
      var(--_sticky-card-stack-peek)
  );
  transform-origin: 50% 0;
  /* This card's share of the stack progress: 0 while uncovered, 1 once the next card covers it.
     Assumes equal card heights (notes.md). */
  --_sticky-card-stack-local: clamp(
    0,
    var(--_sticky-card-stack-progress) * var(--_sticky-card-stack-count) -
      var(--_sticky-card-stack-index),
    1
  );
  --_sticky-card-stack-transform: scale(
    calc(
      1 - var(--_sticky-card-stack-local) *
        (1 - var(--_sticky-card-stack-scale))
    )
  );
  /* filter, not an overlay: follows any card shape the host passes in (D3.4 exception). */
  --_sticky-card-stack-filter: brightness(
    calc(1 - var(--_sticky-card-stack-local) * var(--_sticky-card-stack-dim))
  );
}

@keyframes progress {
  from {
    --_sticky-card-stack-progress: 0;
  }
  to {
    --_sticky-card-stack-progress: 1;
  }
}

/* L1 native (gated on the override attribute, D3.6a). The renderer applies only while a driver
   runs: identity transforms would still create containing blocks for the host's fixed elements. */
@supports (animation-timeline: view()) {
  :root:not([data-fx-layer]) .stack,
  :root[data-fx-layer="native"] .stack {
    animation: progress 1s linear both;
    animation-timeline: view();
    animation-range: exit-crossing;
  }

  :root:not([data-fx-layer]) .card,
  :root[data-fx-layer="native"] .card {
    transform: var(--_sticky-card-stack-transform);
    filter: var(--_sticky-card-stack-filter);
  }
}

/* L2 JS driver. */
.stack[data-layer="js"] .card {
  transform: var(--_sticky-card-stack-transform);
  filter: var(--_sticky-card-stack-filter);
}

/* L3 under reduced motion: cards still stack (sticky is layout), nothing scales or dims. */
@media (prefers-reduced-motion: reduce) {
  :root:not([data-fx-layer]) .stack {
    animation: none;
  }

  :root:not([data-fx-layer]) .card {
    transform: none;
    filter: none;
  }
}

/* Keyboard focus inside a covered card (D3.8): raise the card above the stack and undo its
   shrink and dim, in every layer. :focus-visible, not :focus-within, so a mouse click on a
   button inside a card does not make it jump. Specificity beats the layer rules above. */
:root .stack .card:has(:focus-visible) {
  z-index: 1;
  transform: none;
  filter: none;
}
primitives/frame-scheduler/scheduler.ts
// web-effects frame-scheduler 1.0.0 · MIT-0
// Shared animation-frame scheduler (D3.9). One requestAnimationFrame loop for every caller.
// Each frame runs all `read` callbacks, then all `write` callbacks, so DOM measurements and
// DOM writes never interleave (no forced synchronous layout). Hidden tabs pause it for free,
// because browsers stop requestAnimationFrame there. Pausing off-screen work is the caller's job.

export type FrameTask = {
  /** Measure the DOM. Runs before every write of the same frame. */
  read?: (time: number) => void;
  /** Mutate the DOM (styles, custom properties). */
  write?: (time: number) => void;
};

export type FrameScheduler = {
  /** Runs `task` every frame until the returned function is called. */
  loop: (task: FrameTask) => () => void;
  /** Runs `task` once, on the next frame. Requesting a pending task again is a no-op. */
  once: (task: FrameTask) => () => void;
};

type FrameApi = {
  request: (callback: (time: number) => void) => number;
  cancel: (handle: number) => void;
};

// Resolved per call, not at import, so importing this module is safe during server rendering.
const browserFrames: FrameApi = {
  request: (callback) => requestAnimationFrame(callback),
  cancel: (handle) => cancelAnimationFrame(handle),
};

export function createScheduler(
  frames: FrameApi = browserFrames,
): FrameScheduler {
  const looping = new Set<FrameTask>();
  const pending = new Set<FrameTask>();
  let handle: number | null = null;

  const tick = (time: number) => {
    handle = null;
    const tasks = [...looping, ...pending];
    pending.clear();
    for (const task of tasks) task.read?.(time);
    for (const task of tasks) task.write?.(time);
    if (looping.size > 0 || pending.size > 0) handle = frames.request(tick);
  };

  const start = () => {
    if (handle === null) handle = frames.request(tick);
  };

  const stopIfIdle = () => {
    if (handle !== null && looping.size === 0 && pending.size === 0) {
      frames.cancel(handle);
      handle = null;
    }
  };

  return {
    loop(task) {
      looping.add(task);
      start();
      return () => {
        looping.delete(task);
        stopIfIdle();
      };
    },
    once(task) {
      pending.add(task);
      start();
      return () => {
        pending.delete(task);
        stopIfIdle();
      };
    },
  };
}

/** The scheduler every primitive shares. */
export const frameScheduler: FrameScheduler = createScheduler();
primitives/layer-select/layer.ts
// web-effects layer-select 1.0.0 · MIT-0
// Browser side of layer selection: reads the current inputs and notifies on change.
// Framework-free, for plain-browser hosts; use-layer.ts wraps it for React.
import {
  layerAttribute,
  parseLayer,
  selectLayer,
  type Layer,
} from "./select-layer";

const reducedMotionQuery = "(prefers-reduced-motion: reduce)";

/**
 * The layer for an item whose native layer needs `supports` (an `@supports` condition, the same
 * text as in the item's CSS), or null when the item has no native layer.
 */
export function currentLayer(
  supports: string | null,
  prerequisitesMet = true,
): Layer {
  return selectLayer({
    nativeSupported: supports !== null && CSS.supports(supports),
    reducedMotion: matchMedia(reducedMotionQuery).matches,
    prerequisitesMet,
    override: parseLayer(document.documentElement.getAttribute(layerAttribute)),
  });
}

/** Calls `onChange` when reduced motion or the forced override changes. Returns a stop function. */
export function watchLayerInputs(onChange: () => void): () => void {
  const media = matchMedia(reducedMotionQuery);
  media.addEventListener("change", onChange);
  const observer = new MutationObserver(onChange);
  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: [layerAttribute],
  });
  return () => {
    media.removeEventListener("change", onChange);
    observer.disconnect();
  };
}
primitives/layer-select/select-layer.ts
// web-effects layer-select 1.0.0 · MIT-0
// Layer selection (D2.4, D3.6). CSS decides on its own: `@supports` enables L1, and the base
// rules are the L3 static state, so server-rendered HTML works without JS. JavaScript only
// decides whether to mount an L2 driver; this is that decision, as a pure function.
//
// Forced override (R6.1): an attribute on <html>. Item CSS honours it by writing native-layer
// and reduced-motion rules as `:root:not([data-fx-layer]) .x, :root[data-fx-layer="native"] .x`.
// The showcase sets the attribute from `?driver=`; items never read the host's URL.

export const layers = ["native", "js", "static"] as const;
export type Layer = (typeof layers)[number];

export const layerAttribute = "data-fx-layer";

export function parseLayer(value: string | null | undefined): Layer | null {
  return layers.find((layer) => layer === value) ?? null;
}

export type LayerInputs = {
  /** The item's `@supports` condition holds; false for items without a native layer. */
  nativeSupported: boolean;
  reducedMotion: boolean;
  /** Inputs the effect cannot work without (e.g. a fine pointer) are present. */
  prerequisitesMet: boolean;
  /** Forced layer from the `data-fx-layer` attribute; wins over everything else. */
  override: Layer | null;
};

export function selectLayer({
  nativeSupported,
  reducedMotion,
  prerequisitesMet,
  override,
}: LayerInputs): Layer {
  if (override) return override;
  if (reducedMotion || !prerequisitesMet) return "static";
  return nativeSupported ? "native" : "js";
}
primitives/layer-select/use-layer.ts
// web-effects layer-select 1.0.0 · MIT-0
import { useCallback, useSyncExternalStore } from "react";
import { currentLayer, watchLayerInputs } from "./layer";
import type { Layer } from "./select-layer";

/**
 * The active layer, or null during server rendering and hydration (CSS alone decides until then).
 * Mount the L2 driver when this returns "js".
 */
export function useLayer(
  supports: string | null,
  prerequisitesMet = true,
): Layer | null {
  const getSnapshot = useCallback(
    () => currentLayer(supports, prerequisitesMet),
    [supports, prerequisitesMet],
  );
  return useSyncExternalStore(watchLayerInputs, getSnapshot, () => null);
}
primitives/scroll-progress/scroll-progress.ts
// web-effects scroll-progress 1.0.0 · MIT-0
// L2 scroll-progress driver: writes the `view()` progress of an element into a custom property
// (D2.7). Measures on scroll and resize through the shared scheduler (one read and one write per
// frame at most) and stops measuring while the element is off-screen (D3.9), after writing its
// final clamped value.
import { frameScheduler } from "../frame-scheduler/scheduler";
import { viewProgress, type ViewRange } from "./view-progress";

export type ScrollProgressOptions = {
  /** Custom property to write, the item's private name, e.g. "--_card-stack-progress" (D2.19). */
  property: string;
  range?: ViewRange;
  /**
   * The element's nearest scroll container, as CSS `view()` would pick it. Omit for the page.
   * Not detected automatically: pass it when the subject scrolls inside another element.
   */
  scroller?: HTMLElement;
};

/**
 * The scroller's scrollport (padding box minus a horizontal scrollbar) in viewport coordinates.
 * Fractional on purpose: clientTop/clientHeight round to whole pixels, while view() uses the
 * exact box (a 0.5 px rounding error measurably shifted progress against native).
 */
function scrollport(scroller: HTMLElement): { top: number; height: number } {
  const rect = scroller.getBoundingClientRect();
  const style = getComputedStyle(scroller);
  const borderTop = Number.parseFloat(style.borderTopWidth);
  const borderBottom = Number.parseFloat(style.borderBottomWidth);
  const scrollbar = Math.max(
    0,
    scroller.offsetHeight -
      scroller.clientHeight -
      Math.round(borderTop + borderBottom),
  );
  return {
    top: rect.top + borderTop,
    height: rect.height - borderTop - borderBottom - scrollbar,
  };
}

export function trackScrollProgress(
  element: HTMLElement,
  { property, range = "cover", scroller }: ScrollProgressOptions,
): () => void {
  let progress = Number.NaN;
  let written = Number.NaN;
  let visible = true;

  const task = {
    read() {
      const rect = element.getBoundingClientRect();
      const port = scroller
        ? scrollport(scroller)
        : { top: 0, height: document.documentElement.clientHeight };
      progress = viewProgress(range, {
        top: rect.top - port.top,
        height: rect.height,
        viewport: port.height,
      });
    },
    write() {
      if (progress === written) return;
      element.style.setProperty(property, String(progress));
      written = progress;
    },
  };

  const request = () => {
    if (visible) frameScheduler.once(task);
  };
  const cancelPending = frameScheduler.once(task);

  const observer = new IntersectionObserver(
    ([entry]) => {
      visible = entry.isIntersecting;
      // One measurement on every visibility change, so leaving the viewport writes 0 or 1.
      frameScheduler.once(task);
    },
    { root: scroller ?? null },
  );
  observer.observe(element);

  const target: HTMLElement | Window = scroller ?? window;
  target.addEventListener("scroll", request, { passive: true });
  window.addEventListener("resize", request, { passive: true });

  return () => {
    cancelPending();
    observer.disconnect();
    target.removeEventListener("scroll", request);
    window.removeEventListener("resize", request);
    element.style.removeProperty(property);
  };
}
primitives/scroll-progress/use-scroll-progress.ts
// web-effects scroll-progress 1.0.0 · MIT-0
import { useEffect, type RefObject } from "react";
import { trackScrollProgress } from "./scroll-progress";
import type { ViewRange } from "./view-progress";

/** Runs the L2 driver on `ref` while `enabled` (typically `useLayer(...) === "js"`). */
export function useScrollProgress(
  ref: RefObject<HTMLElement | null>,
  {
    enabled,
    property,
    range = "cover",
    scroller,
  }: {
    enabled: boolean;
    property: string;
    range?: ViewRange;
    scroller?: RefObject<HTMLElement | null>;
  },
) {
  useEffect(() => {
    const element = ref.current;
    if (!enabled || !element) return;
    return trackScrollProgress(element, {
      property,
      range,
      scroller: scroller?.current ?? undefined,
    });
  }, [ref, enabled, property, range, scroller]);
}
primitives/scroll-progress/view-progress.ts
// web-effects scroll-progress 1.0.0 · MIT-0
// Progress of a subject through its scrollport, matching the CSS `view()` timeline (block
// axis, no inset) for the `cover`, `contain` and `exit-crossing` ranges. The L2 driver writes this value so
// that item CSS renders identically on L1 (native timeline) and L2 (D2.7).

export const viewRanges = ["cover", "contain", "exit-crossing"] as const;
export type ViewRange = (typeof viewRanges)[number];

export type ViewGeometry = {
  /** Subject's top edge, relative to the scrollport's top edge, in px. */
  top: number;
  /** Subject's height in px. */
  height: number;
  /** Scrollport's height in px. */
  viewport: number;
};

/**
 * 0 at the start of the range, 1 at its end, clamped. Positions are expressed as the subject's
 * top edge: progress grows as `top` decreases (content scrolls up).
 *   cover:   from the subject's top at the scrollport's bottom (top = viewport)
 *            to its bottom at the scrollport's top (top = -height).
 *   contain: from the subject fully inside, or fully covering, the scrollport for the first time
 *            to the last time; when it is exactly as tall as the scrollport the range is a point.
 *   exit-crossing: from the subject's top at the scrollport's top (top = 0) to its bottom there
 *            (top = -height); progress follows scroll distance over the subject's own height.
 */
export function viewProgress(
  range: ViewRange,
  { top, height, viewport }: ViewGeometry,
): number {
  const [start, end] = rangeEdges(range, height, viewport);
  if (start === end) return top > start ? 0 : 1;
  return Math.min(Math.max((start - top) / (start - end), 0), 1);
}

/** Range start and end, as values of the subject's `top`. */
function rangeEdges(
  range: ViewRange,
  height: number,
  viewport: number,
): [number, number] {
  switch (range) {
    case "cover":
      return [viewport, -height];
    case "contain":
      return [Math.max(viewport - height, 0), Math.min(viewport - height, 0)];
    case "exit-crossing":
      return [0, -height];
  }
}
tailwind/StickyCardStack.tsx
// web-effects sticky-card-stack 1.0.0 · MIT-0
"use client";

import { Children, type ReactNode } from "react";
import mechanism from "../mechanism.module.css";
import { useStickyCardStack } from "../use-sticky-card-stack";

/** Cards that stick near the top and stack; each covered card shrinks and dims. One child per card. */
export function StickyCardStack({
  children,
  className = "",
}: {
  children: ReactNode;
  className?: string;
}) {
  const cards = Children.toArray(children);
  const { stackProps, cardStyle } = useStickyCardStack(cards.length);
  return (
    <ol
      {...stackProps}
      className={`${mechanism.stack} flex flex-col gap-6 ${className}`}
    >
      {cards.map((card, index) => (
        <li key={index} className={mechanism.card} style={cardStyle(index)}>
          {card}
        </li>
      ))}
    </ol>
  );
}
use-sticky-card-stack.ts
// web-effects sticky-card-stack 1.0.0 · MIT-0
import { useRef, type CSSProperties } from "react";
import { useLayer } from "./primitives/layer-select/use-layer";
import { useScrollProgress } from "./primitives/scroll-progress/use-scroll-progress";

// Behaviour shared by both styling variants (P8): layer decision, the L2 driver, and the inline
// custom properties the mechanism CSS reads. The variants add presentation classes only.

export function useStickyCardStack(count: number) {
  const ref = useRef<HTMLOListElement>(null);
  // Literal on purpose: the generator checks it against the CSS @supports condition (D3.6b).
  const driven = useLayer("(animation-timeline: view())") === "js";
  useScrollProgress(ref, {
    enabled: driven,
    property: "--_sticky-card-stack-progress",
    range: "exit-crossing",
  });

  return {
    stackProps: {
      ref,
      "data-layer": driven ? "js" : undefined,
      style: { "--_sticky-card-stack-count": count } as CSSProperties,
    },
    cardStyle: (index: number) =>
      ({ "--_sticky-card-stack-index": index }) as CSSProperties,
  };
}