# Stacking Cards

Cards that stick and pile up as you scroll, while the covered ones shrink, fan out, or blur. A card with keyboard focus comes back to the front.

- Category: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/stacking-cards.json
- CLI: `npx markasui@latest add stacking-cards`

## When to use

Scroll stories made of 3 to 6 steps or features: product features, onboarding steps, pricing plans, testimonials, or a short company timeline.

- Every direct child is a card, so give each a solid background, a border, and the same height
- Leave scroll room after the stack (padding or another section) so the last card can settle
- Use an article or a list item per card when the cards carry headings
- Keep 3 to 6 cards; more turns the effect into a chore

## Code

### Blade

Save at `resources/views/components/markas/stacking-cards.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'variant' => 'scale',
    'top' => 16,
    'offset' => 16,
])

@php
    $base = 'relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]';
    $variants = [
        'scale' => '[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]',
        'fan' => '[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]',
        'blur' => '[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]',
    ];
    $style = '--stack-top: '.(float) $top.'px; --stack-step: '.(float) $offset.'px';
@endphp

{{-- Every card gets its index; while on screen, --stack-depth says how much the later cards already cover it. --}}
<div
    wire:ignore
    x-data="{
        frame: 0,
        observer: null,
        stop: null,
        init() {
            const root = this.$root;
            const step = {{ (float) $offset }};
            const cards = () => [...root.children];
            cards().forEach((card, i) => {
                card.style.setProperty('--stack-i', String(i));
                card.style.setProperty('--stack-turn', i % 2 ? '1' : '-1');
            });
            if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches || typeof IntersectionObserver !== 'function') return;
            const clamp = (n) => Math.min(Math.max(n, 0), 1);
            const update = () => {
                this.frame = 0;
                const list = cards();
                let depth = 0;
                for (let i = list.length - 1; i >= 0; i--) {
                    const card = list[i];
                    card.style.setProperty('--stack-depth', String(Math.round(Math.min(depth, 6) * 1000) / 1000));
                    const prev = list[i - 1];
                    if (! prev) continue;
                    const gap = card.offsetTop - prev.offsetTop;
                    depth += clamp((prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1));
                }
            };
            const schedule = () => {
                this.frame ||= requestAnimationFrame(update);
            };
            const listen = (on) => {
                const method = on ? 'addEventListener' : 'removeEventListener';
                document[method]('scroll', schedule, { capture: true, passive: true });
                window[method]('resize', schedule);
            };
            this.observer = new IntersectionObserver(([entry]) => {
                listen(Boolean(entry?.isIntersecting));
                schedule();
            });
            this.observer.observe(root);
            this.stop = () => listen(false);
        },
        destroy() {
            this.observer?.disconnect();
            this.stop?.();
            cancelAnimationFrame(this.frame);
        },
    }"
    {{ $attributes->merge(['style' => $style])->class([$base, $variants[$variant] ?? $variants['scale']]) }}
>
    {{ $slot }}
</div>
```

```blade
<div class="pb-64">
    <x-markas.stacking-cards variant="fan" :top="96" :offset="12" class="gap-6">
        <article class="h-64 rounded-xl border border-line bg-surface p-6">Plan your week</article>
        <article class="h-64 rounded-xl border border-line bg-surface p-6">Share with your team</article>
        <article class="h-64 rounded-xl border border-line bg-surface p-6">Get paid on time</article>
    </x-markas.stacking-cards>
</div>
```

Needs Alpine.js.

### React

Save at `src/components/markas/StackingCards.tsx`. No extra dependencies.

```tsx
"use client";

import { useEffect, useRef, type ComponentProps } from "react";

export type StackingCardsVariant = "scale" | "fan" | "blur";

const base =
  "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
const variants: Record<StackingCardsVariant, string> = {
  scale:
    "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
  fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
  blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
};

const MAX_DEPTH = 6;

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

/**
 * Give every card its index, then, while the stack is on screen, set --stack-depth on each card:
 * how many of the cards after it already cover it (0 to 1 each), from layout boxes that ignore transforms.
 */
function createStack(root: HTMLElement, step: number) {
  const cards = () => [...root.children] as HTMLElement[];
  cards().forEach((card, i) => {
    card.style.setProperty("--stack-i", String(i));
    card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
  });
  if (still() || typeof IntersectionObserver !== "function") return () => {};

  let frame = 0;
  const update = () => {
    frame = 0;
    const list = cards();
    let depth = 0;
    for (let i = list.length - 1; i >= 0; i--) {
      const card = list[i]!;
      card.style.setProperty(
        "--stack-depth",
        String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
      );
      const prev = list[i - 1];
      if (!prev) continue;
      const gap = card.offsetTop - prev.offsetTop;
      depth += clamp(
        (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
      );
    }
  };
  const schedule = () => {
    frame ||= requestAnimationFrame(update);
  };
  const listen = (on: boolean) => {
    const method = on ? "addEventListener" : "removeEventListener";
    document[method]("scroll", schedule, { capture: true, passive: true });
    window[method]("resize", schedule);
  };
  const observer = new IntersectionObserver(([entry]) => {
    listen(Boolean(entry?.isIntersecting));
    schedule();
  });
  observer.observe(root);
  return () => {
    observer.disconnect();
    listen(false);
    cancelAnimationFrame(frame);
  };
}

export type StackingCardsProps = ComponentProps<"div"> & {
  /** What happens to the cards that the next ones cover. */
  variant?: StackingCardsVariant;
  /** Sticky top of the first card in px. */
  top?: number;
  /** Extra px each later card sticks below the one before, so earlier cards peek out. */
  offset?: number;
};

export function StackingCards({
  variant = "scale",
  top = 16,
  offset = 16,
  className,
  style,
  children,
  ...props
}: StackingCardsProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  useEffect(() => createStack(rootRef.current!, offset), [offset]);
  return (
    <div
      {...props}
      ref={rootRef}
      className={cx(base, variants[variant], className)}
      style={
        {
          "--stack-top": `${top}px`,
          "--stack-step": `${offset}px`,
          ...style,
        } as ComponentProps<"div">["style"]
      }
    >
      {children}
    </div>
  );
}
```

```tsx
import { StackingCards } from "@/components/markas/StackingCards";

<div className="pb-64">
  <StackingCards variant="fan" top={96} offset={12} className="gap-6">
    <article className="h-64 rounded-xl border border-line bg-surface p-6">
      Plan your week
    </article>
    <article className="h-64 rounded-xl border border-line bg-surface p-6">
      Share with your team
    </article>
    <article className="h-64 rounded-xl border border-line bg-surface p-6">
      Get paid on time
    </article>
  </StackingCards>
</div>;
```

### Vue

Save at `src/components/markas/StackingCards.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from "vue";

export type StackingCardsVariant = "scale" | "fan" | "blur";

const props = withDefaults(
  defineProps<{
    /** What happens to the cards that the next ones cover. */
    variant?: StackingCardsVariant;
    /** Sticky top of the first card in px. */
    top?: number;
    /** Extra px each later card sticks below the one before, so earlier cards peek out. */
    offset?: number;
  }>(),
  { variant: "scale", top: 16, offset: 16 },
);

const base =
  "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
const variants: Record<StackingCardsVariant, string> = {
  scale:
    "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
  fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
  blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
};

const MAX_DEPTH = 6;

const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

/**
 * Give every card its index, then, while the stack is on screen, set --stack-depth on each card:
 * how many of the cards after it already cover it (0 to 1 each), from layout boxes that ignore transforms.
 */
function createStack(root: HTMLElement, step: number) {
  const cards = () => [...root.children] as HTMLElement[];
  cards().forEach((card, i) => {
    card.style.setProperty("--stack-i", String(i));
    card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
  });
  if (still() || typeof IntersectionObserver !== "function") return () => {};

  let frame = 0;
  const update = () => {
    frame = 0;
    const list = cards();
    let depth = 0;
    for (let i = list.length - 1; i >= 0; i--) {
      const card = list[i]!;
      card.style.setProperty(
        "--stack-depth",
        String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
      );
      const prev = list[i - 1];
      if (!prev) continue;
      const gap = card.offsetTop - prev.offsetTop;
      depth += clamp(
        (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
      );
    }
  };
  const schedule = () => {
    frame ||= requestAnimationFrame(update);
  };
  const listen = (on: boolean) => {
    const method = on ? "addEventListener" : "removeEventListener";
    document[method]("scroll", schedule, { capture: true, passive: true });
    window[method]("resize", schedule);
  };
  const observer = new IntersectionObserver(([entry]) => {
    listen(Boolean(entry?.isIntersecting));
    schedule();
  });
  observer.observe(root);
  return () => {
    observer.disconnect();
    listen(false);
    cancelAnimationFrame(frame);
  };
}

const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
let stop = () => {};
const start = () => {
  stop();
  stop = createStack(rootEl.value!, props.offset);
};
onMounted(start);
watch(() => props.offset, start);
onBeforeUnmount(() => stop());
</script>

<template>
  <div
    ref="rootRef"
    :class="[base, variants[props.variant]]"
    :style="{
      '--stack-top': `${props.top}px`,
      '--stack-step': `${props.offset}px`,
    }"
  >
    <slot />
  </div>
</template>
```

```vue
<template>
  <div class="pb-64">
    <StackingCards variant="fan" :top="96" :offset="12" class="gap-6">
      <article class="h-64 rounded-xl border border-line bg-surface p-6">
        Plan your week
      </article>
      <article class="h-64 rounded-xl border border-line bg-surface p-6">
        Share with your team
      </article>
      <article class="h-64 rounded-xl border border-line bg-surface p-6">
        Get paid on time
      </article>
    </StackingCards>
  </div>
</template>
```

### Svelte

Save at `src/lib/components/markas/StackingCards.svelte`. No extra dependencies.

```svelte
<script lang="ts">
  import type { Snippet } from "svelte";
  import type { HTMLAttributes } from "svelte/elements";

  type StackingCardsVariant = "scale" | "fan" | "blur";

  const base =
    "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
  const variants: Record<StackingCardsVariant, string> = {
    scale:
      "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
    fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
    blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
  };

  const MAX_DEPTH = 6;

  const still = () =>
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

  /**
   * Give every card its index, then, while the stack is on screen, set --stack-depth on each card:
   * how many of the cards after it already cover it (0 to 1 each), from layout boxes that ignore transforms.
   */
  function createStack(root: HTMLElement, step: number) {
    const cards = () => [...root.children] as HTMLElement[];
    cards().forEach((card, i) => {
      card.style.setProperty("--stack-i", String(i));
      card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
    });
    if (still() || typeof IntersectionObserver !== "function") return () => {};

    let frame = 0;
    const update = () => {
      frame = 0;
      const list = cards();
      let depth = 0;
      for (let i = list.length - 1; i >= 0; i--) {
        const card = list[i]!;
        card.style.setProperty(
          "--stack-depth",
          String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
        );
        const prev = list[i - 1];
        if (!prev) continue;
        const gap = card.offsetTop - prev.offsetTop;
        depth += clamp(
          (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
        );
      }
    };
    const schedule = () => {
      frame ||= requestAnimationFrame(update);
    };
    const listen = (on: boolean) => {
      const method = on ? "addEventListener" : "removeEventListener";
      document[method]("scroll", schedule, { capture: true, passive: true });
      window[method]("resize", schedule);
    };
    const observer = new IntersectionObserver(([entry]) => {
      listen(Boolean(entry?.isIntersecting));
      schedule();
    });
    observer.observe(root);
    return () => {
      observer.disconnect();
      listen(false);
      cancelAnimationFrame(frame);
    };
  }

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** What happens to the cards that the next ones cover. */
    variant?: StackingCardsVariant;
    /** Sticky top of the first card in px. */
    top?: number;
    /** Extra px each later card sticks below the one before, so earlier cards peek out. */
    offset?: number;
    children?: Snippet;
  };

  let {
    variant = "scale",
    top = 16,
    offset = 16,
    class: className,
    style,
    children,
    ...rest
  }: Props = $props();

  let root = $state<HTMLDivElement>();

  $effect(() => {
    const step = offset;
    if (root) return createStack(root, step);
  });
</script>

<div
  {...rest}
  bind:this={root}
  class={[base, variants[variant], className]}
  style={`--stack-top: ${top}px; --stack-step: ${offset}px;${style ? ` ${style}` : ""}`}
>
  {@render children?.()}
</div>
```

```svelte
<script lang="ts">
  import StackingCards from "$lib/components/markas/StackingCards.svelte";
</script>

<StackingCards variant="fan" class="gap-4">
  <article class="h-48 rounded-xl border border-line bg-surface p-5">
    One
  </article>
  <article class="h-48 rounded-xl border border-line bg-surface p-5">
    Two
  </article>
</StackingCards>
```

### Astro

Save at `src/components/markas/StackingCards.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

type StackingCardsVariant = "scale" | "fan" | "blur";

const base =
  "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
const variants: Record<StackingCardsVariant, string> = {
  scale:
    "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
  fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
  blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
};

type Props = HTMLAttributes<"div"> & {
  /** What happens to the cards that the next ones cover. */
  variant?: StackingCardsVariant;
  /** Sticky top of the first card in px. */
  top?: number;
  /** Extra px each later card sticks below the one before, so earlier cards peek out. */
  offset?: number;
};

const {
  variant = "scale",
  top = 16,
  offset = 16,
  class: className,
  style,
  ...rest
} = Astro.props;
const userStyle = typeof style === "string" && style ? ` ${style}` : "";
---

<markas-stacking-cards class="contents">
  <div
    {...rest}
    class:list={[base, variants[variant], className]}
    style={`--stack-top: ${top}px; --stack-step: ${offset}px;${userStyle}`}
  >
    <slot />
  </div>
</markas-stacking-cards>

<script>
  const MAX_DEPTH = 6;
  const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

  /**
   * Per instance: give every card its index, then, while the stack is on screen, set --stack-depth
   * on each card: how many of the cards after it already cover it (0 to 1 each), from layout boxes
   * that ignore transforms.
   */
  class StackingCards extends HTMLElement {
    #stop = () => {};

    connectedCallback() {
      const root = this.firstElementChild as HTMLElement | null;
      if (!root) return;
      const step = parseFloat(root.style.getPropertyValue("--stack-step")) || 0;
      const cards = () => [...root.children] as HTMLElement[];
      cards().forEach((card, i) => {
        card.style.setProperty("--stack-i", String(i));
        card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
      });
      if (
        window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ||
        typeof IntersectionObserver !== "function"
      )
        return;

      let frame = 0;
      const update = () => {
        frame = 0;
        const list = cards();
        let depth = 0;
        for (let i = list.length - 1; i >= 0; i--) {
          const card = list[i]!;
          card.style.setProperty(
            "--stack-depth",
            String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
          );
          const prev = list[i - 1];
          if (!prev) continue;
          const gap = card.offsetTop - prev.offsetTop;
          depth += clamp(
            (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
          );
        }
      };
      const schedule = () => {
        frame ||= requestAnimationFrame(update);
      };
      const listen = (on: boolean) => {
        const method = on ? "addEventListener" : "removeEventListener";
        document[method]("scroll", schedule, { capture: true, passive: true });
        window[method]("resize", schedule);
      };
      const observer = new IntersectionObserver(([entry]) => {
        listen(Boolean(entry?.isIntersecting));
        schedule();
      });
      observer.observe(root);
      this.#stop = () => {
        observer.disconnect();
        listen(false);
        cancelAnimationFrame(frame);
      };
    }

    disconnectedCallback() {
      this.#stop();
    }
  }

  if (!customElements.get("markas-stacking-cards"))
    customElements.define("markas-stacking-cards", StackingCards);
</script>
```

```astro
---
import StackingCards from "@/components/markas/StackingCards.astro";
---

<StackingCards variant="fan" class="gap-4">
  <article class="h-48 rounded-xl border border-line bg-surface p-5">One</article>
  <article class="h-48 rounded-xl border border-line bg-surface p-5">Two</article>
</StackingCards>
```

A small bundled script measures each stack through the `markas-stacking-cards` element.

### Angular

Save at `src/app/markas/stacking-cards.component.ts`. No extra dependencies.

```ts
import {
  afterRenderEffect,
  ChangeDetectionStrategy,
  Component,
  computed,
  type ElementRef,
  input,
  numberAttribute,
  viewChild,
} from "@angular/core";

export type StackingCardsVariant = "scale" | "fan" | "blur";

const base =
  "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
const variants: Record<StackingCardsVariant, string> = {
  scale:
    "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
  fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
  blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
};

const MAX_DEPTH = 6;

const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

/**
 * Give every card its index, then, while the stack is on screen, set --stack-depth on each card:
 * how many of the cards after it already cover it (0 to 1 each), from layout boxes that ignore transforms.
 */
function createStack(root: HTMLElement, step: number) {
  const cards = () => [...root.children] as HTMLElement[];
  cards().forEach((card, i) => {
    card.style.setProperty("--stack-i", String(i));
    card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
  });
  if (still() || typeof IntersectionObserver !== "function") return () => {};

  let frame = 0;
  const update = () => {
    frame = 0;
    const list = cards();
    let depth = 0;
    for (let i = list.length - 1; i >= 0; i--) {
      const card = list[i]!;
      card.style.setProperty(
        "--stack-depth",
        String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
      );
      const prev = list[i - 1];
      if (!prev) continue;
      const gap = card.offsetTop - prev.offsetTop;
      depth += clamp(
        (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
      );
    }
  };
  const schedule = () => {
    frame ||= requestAnimationFrame(update);
  };
  const listen = (on: boolean) => {
    const method = on ? "addEventListener" : "removeEventListener";
    document[method]("scroll", schedule, { capture: true, passive: true });
    window[method]("resize", schedule);
  };
  const observer = new IntersectionObserver(([entry]) => {
    listen(Boolean(entry?.isIntersecting));
    schedule();
  });
  observer.observe(root);
  return () => {
    observer.disconnect();
    listen(false);
    cancelAnimationFrame(frame);
  };
}

/** Every projected element is one card. The host stays out of layout; the user's class and role land on the stack. */
@Component({
  selector: "markas-stacking-cards",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.role]": "null" },
  template: `
    <div
      #rootEl
      [attr.role]="role()"
      [class]="classes()"
      [style.--stack-top]="top() + 'px'"
      [style.--stack-step]="offset() + 'px'"
    >
      <ng-content />
    </div>
  `,
})
export class StackingCards {
  /** What happens to the cards that the next ones cover. */
  readonly variant = input<StackingCardsVariant>("scale");
  /** Sticky top of the first card in px. */
  readonly top = input(16, { transform: numberAttribute });
  /** Extra px each later card sticks below the one before, so earlier cards peek out. */
  readonly offset = input(16, { transform: numberAttribute });
  /** Lands on the stack, for example role="list" around li cards. */
  readonly role = input<string>();
  readonly userClass = input("", { alias: "class" });

  protected readonly classes = computed(() =>
    [base, variants[this.variant()], this.userClass()]
      .filter(Boolean)
      .join(" "),
  );
  private readonly root = viewChild.required<ElementRef<HTMLElement>>("rootEl");

  constructor() {
    afterRenderEffect((onCleanup) => {
      onCleanup(createStack(this.root().nativeElement, this.offset()));
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { StackingCards } from "./markas/stacking-cards.component";

@Component({
  selector: "app-features",
  imports: [StackingCards],
  template: `
    <markas-stacking-cards variant="fan" class="gap-4">
      <article class="h-48 rounded-xl border border-line bg-surface p-5">
        One
      </article>
      <article class="h-48 rounded-xl border border-line bg-surface p-5">
        Two
      </article>
    </markas-stacking-cards>
  `,
})
export class Features {}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `variant` | `"scale" \| "fan" \| "blur"` | "scale" | What happens to covered cards. scale: shrink and dim. fan: tilt left and right like a deck. blur: blur and dim. |
| `top` | `number` | 16 | Sticky top of the first card in px, measured from the top of the scrolling area. |
| `offset` | `number` | 16 | Extra px each later card sticks below the one before, so the edges of earlier cards peek out. 0 stacks them exactly. |
| `children / slot` | `ReactNode / slot` | - | The cards. Every direct child is one card; give each its own background so it covers the ones below. |

## Accessibility

- Cards stay in normal reading order; the stacking is only visual.
- A card that holds keyboard focus jumps to the front at full size, so focus is never hidden behind later cards.
- With reduced motion the cards still stick but never shrink, tilt, or blur.

## Notes

- Every direct child is a card. Cards stick at `top` plus `offset` per card, so earlier cards peek out above the later ones.
- `--stack-depth` on each card says how much the later cards already cover it. `scale` shrinks and dims, `fan` tilts left and right, `blur` blurs and dims.
- The scroll listener is passive, batched into one requestAnimationFrame, and only attached while the stack is on screen. It works in the page and inside any scrolling container.
- A card holding keyboard focus jumps to the front at full size. With reduced motion the cards still stick but never change. Attributes and `class` go to the stack.
