Skip to content

176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.

27.5 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Stacking Cards — Animation Handbook</title>
  <meta name="description" content="Cards stick at the top and pile into a deck. Best for step-by-step stories.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/stacking-cards/">
  <link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
  <link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
  <link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
  <meta property="og:type" content="article">
  <meta property="og:site_name" content="Animation Handbook">
  <meta property="og:title" content="Stacking Cards — Animation Handbook">
  <meta property="og:description" content="Cards stick at the top and pile into a deck. Best for step-by-step stories.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/stacking-cards/">
  <meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="Stacking Cards — Animation Handbook">
  <meta name="twitter:description" content="Cards stick at the top and pile into a deck. Best for step-by-step stories.">
  <meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Stacking Cards", "name": "Stacking Cards", "description": "Cards stick at the top and pile into a deck. Best for step-by-step stories.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/stacking-cards/", "inLanguage": "en", "articleSection": "Scroll-Based", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Scroll-Based, Stacking Cards"}</script>
  <style>
    :root{--ui-accent:#6ea8ff;--scale-step:0.10;--peek:14px}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    /* stage: the ONLY scroll container. no overflow on any descendant above .card */
    .stage{position:relative;overflow-y:auto;scrollbar-width:none;container-type:size;background:#0b0b0d}
    .stage::-webkit-scrollbar{display:none}
    /* lead-in: enough to scroll the first card up into the stack, but not so much
       that the demo opens on an empty stage */
    .spacer{height:25cqh}
    #cards{--numcards:5;view-timeline-name:--cards-timeline;view-timeline-axis:block}
    /* The run-out MUST be a real child of #cards. A sticky card stays pinned only
       while its containing block extends below it, and the last card's bottom is
       flush with the last card — so a spacer *after* #cards let the finished deck
       slide straight off the top. Padding does not work either: the sticky
       constraint is the containing block's content box, which excludes padding.
       This element's height is the pinned window — how far you can keep scrolling
       with the completed deck held on screen. */
    .run-out{height:30cqh}
    /* sticky is on .card — the outer wrapper — NOT on .card__content */
    .card{
      --index0:calc(var(--index) - 1);
      --reverse-index:calc(var(--numcards) - var(--index0));
      position:sticky;
      top:0;
      /* padding-top staggers each card's content lower, making previous cards peek above */
      padding-top:calc(var(--index0) * var(--peek));
      z-index:var(--index);
    }
    .card__content{
      /* Each card's total height is content + its peek padding, and the last card
         carries the tallest stack of it. Subtracting the peek run keeps every card
         within the stage, so the deepest card never clips at high card counts. */
      height:calc(100cqh - 12px - (var(--numcards) - 1) * var(--peek));
      border-radius:16px;overflow:hidden;
      display:grid;grid-template-columns:55fr 45fr;
      box-shadow:0 16px 56px rgba(0,0,0,.65);
      background:#fff;color:#1a1a1a;
      /* scale collapses downward from the top edge, keeping peek tabs visible */
      transform-origin:50% 0%;
      position:relative;
    }
    @keyframes card-scale{
      to{transform:scale(calc(1 + var(--scale-step) - var(--scale-step) * var(--reverse-index)))}
    }
    @supports(animation-timeline:scroll()){
      #cards:not(.js-fallback) .card__content{
        --start-range:calc(var(--index0) / var(--numcards) * 100%);
        --end-range:calc(var(--index) / var(--numcards) * 100%);
        animation:linear card-scale both;
        animation-timeline:--cards-timeline;
        animation-range:exit-crossing var(--start-range) exit-crossing var(--end-range);
      }
    }
    .card__text{position:relative;padding:clamp(14px,6cqh,32px) clamp(18px,3vw,32px);display:flex;flex-direction:column;justify-content:center;gap:10px}
    /* the big faded number is a watermark, so it takes no room from the text */
    .card-num{position:absolute;top:clamp(8px,3cqh,16px);right:clamp(12px,2.5vw,24px);margin:0;font-size:52px;font-weight:bold;opacity:.1;line-height:1}
    .card-title{font-size:clamp(16px,2.2vw,22px);font-weight:bold;color:#111;line-height:1.2}
    .card-sub{font-size:11px;color:#5f5f66;text-transform:uppercase;letter-spacing:1.5px}
    .card-body{font-size:14px;color:#5f5f66;line-height:1.65;max-width:320px}
    /* on the shortest cards the line hides and the rest sits closer, so the title, the kind and the button fit */
    #cards.short .card-body{display:none}
    #cards.short .card__text{gap:6px}
    .card-btn{align-self:flex-start;border:1px solid var(--ac,#888);color:var(--ac,#888);font-size:11px;padding:8px 14px;border-radius:4px;letter-spacing:1px;margin-top:4px}
    .card__visual{overflow:hidden}
    @media(max-width:600px){.card__content{grid-template-columns:1fr;grid-template-rows:1fr}.card__visual{display:none}.card__text{gap:6px}}
    @media(prefers-reduced-motion:reduce){.card__content{animation:none!important}}

    /* See inside: a comb of dashed lines across the top of the box, one where each card stops (a strip lower each time),
       bright once that card is stuck. Behind each card a faint dashed outline of its full size sits on the card's unscaled
       wrapper, so it sticks and is covered with its card, and the gap beside the shrunken card is the shrink.
       Compare: a plain list beside the real deck, scrolling together; the list is no taller than the deck. */
    .lay,.copy,.tick,.cap,.mid{display:none}
    .lay{position:sticky;top:0;height:0;z-index:30;pointer-events:none;--n:5}
    .tick{position:absolute;left:0;right:0;top:calc(var(--i) * var(--peek));border-top:2px dashed rgba(110,168,255,.5)}
    .tick.on{border-top-color:#8fbcff}
    .cap{position:absolute;padding:5px 10px;border-radius:999px;white-space:nowrap;background:rgba(11,11,13,.9);color:#f4f4f2;
      border:1px solid rgba(244,244,242,.3);font:600 13px/1.2 var(--hb-font)}
    /* the two labels sit below the comb, at the right where the cards have no text, the wider one first */
    .in-b{top:calc((var(--n) - 1) * var(--peek) + 10px);right:8px;border-color:#ffd27a}
    .in-a{top:calc((var(--n) - 1) * var(--peek) + 42px);right:8px;border-color:#8fbcff}
    .cmp-a,.cmp-b{top:6px}
    .cmp-a{right:calc(50% + 9px)}.cmp-b{right:8px}
    .mid{position:absolute;left:calc(50% - 1px);width:2px;top:0;height:100cqh;background:rgba(244,244,242,.35)}
    .copy{position:absolute;top:25cqh;left:0;width:calc(50% - 1px);--numcards:5;flex-direction:column;gap:10px}
    .copy.short .card-body{display:none}
    .copy.short .card__text{gap:6px}
    .card{--end:calc(1 + var(--scale-step) - var(--scale-step) * var(--reverse-index))}
    .stage[data-hb-mode="inside"] .lay,.stage[data-hb-mode="compare"] .lay{display:block}
    .stage[data-hb-mode="inside"] .tick,.stage[data-hb-mode="inside"] .in-a,.stage[data-hb-mode="inside"] .in-b,
    .stage[data-hb-mode="compare"] .cap.cmp-a,.stage[data-hb-mode="compare"] .cap.cmp-b,.stage[data-hb-mode="compare"] .mid{display:block}
    .stage[data-hb-mode="inside"] .card.covered::after{content:"";position:absolute;left:0;right:0;bottom:0;top:calc(var(--index0) * var(--peek));
      z-index:-1;border:2px dashed rgba(255,210,122,.95);border-radius:16px;background:rgba(255,210,122,.3);pointer-events:none}
    /* Phones: the cards' text runs the full width, so the two labels wrap into a narrow column at the right and See inside
       leaves that column free of text */
    @media(max-width:600px){
      .stage[data-hb-mode="inside"] .cap{white-space:normal;width:116px;text-align:center;padding:4px 6px;border-radius:14px;line-height:1.15}
      .stage[data-hb-mode="inside"] .in-b{top:calc((var(--n) - 1) * var(--peek) + 8px)}
      .stage[data-hb-mode="inside"] .in-a{top:calc((var(--n) - 1) * var(--peek) + 54px)}
      .stage[data-hb-mode="inside"] .card__text{padding-right:130px}
    }
    .stage[data-hb-mode="compare"] .copy{display:flex}
    .stage[data-hb-mode="compare"] #cards{margin-left:50%}
    /* Reduced motion: nothing shrinks, so each covered card shows an inner outline of the size it would shrink to */
    @media(prefers-reduced-motion:reduce){
      .stage[data-hb-mode="inside"] .card.covered::after{z-index:auto;left:calc((1 - var(--end)) / 2 * 100%);right:calc((1 - var(--end)) / 2 * 100%);
        background:none;border-color:#b87800;border-radius:12px}
    }
  </style>
  <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
  <script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="scroll" data-hb-autoplay data-hb-motion-note="The cards stack without shrinking">
<nav class="hb-bar" aria-label="Animation Handbook">
  <a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
  <span class="hb-pager"><a href="../fly-in-fly-out-contact-list/" rel="prev" aria-label="Previous: Fly-in Fly-out Contact List"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Fly-in Fly-out Contact List</span></a><a href="../scroll-trigger/" rel="next" aria-label="Next: Scroll-Triggered Animation"><span><span class="hb-dir">Next: </span>Scroll-Triggered Animation</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
  <a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
  <header class="hb-head">
    <p class="hb-cat">01.06 · Scroll-Based</p>
    <h1>Stacking Cards</h1>
    <p class="hb-lede">Cards stick at the top and pile into a deck. Best for step-by-step stories.</p>
  </header>

  <section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">1</span>
      <div><h2 id="hb-watch-title">Scroll it</h2><p>Scroll inside the box, or press Play and it scrolls for you.</p></div>
    </div>
    <div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
      <button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
      <button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
      <button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
    </div>
    <div class="stage" id="stage" tabindex="0" role="region" aria-label="A stack of project cards">
      <div class="lay" id="lay" aria-hidden="true" inert>
        <span class="mid"></span><span id="ticks"></span>
        <p class="cap in-a" data-hb-caption>Where each card stops</p>
        <p class="cap in-b" data-hb-caption id="cap-full">Full size before it shrank</p>
        <p class="cap cmp-a" data-hb-caption>Scroll past</p>
        <p class="cap cmp-b" data-hb-caption>Stack up</p>
      </div>
      <div class="copy" id="copy" aria-hidden="true" inert></div>
      <div class="spacer"></div>
      <div id="cards"></div>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-scroll" data-hb-autoscroll><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M19 12l-7 7-7-7"/></svg>Play</button>
      <button class="hb-play" type="button" id="btn-top" data-hb-top><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>Back to top</button>
    </div>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>Inside, the dashed lines mark where each card stops, a strip lower than the last, and faint outlines show each covered card's full size. Scroll the box or press Play to watch.</p>
      <p data-hb-for="compare" hidden>In Scroll past, cards go by like a plain list; in Stack up, each sticks at the top and the next slides over it, leaving a strip. Scroll the box or press Play to watch.</p>
    </div>
  </section>

  <section class="hb-step hb-try" aria-labelledby="hb-try-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">2</span>
      <div><h2 id="hb-try-title">Try it</h2><p>Change a setting, then scroll again or press Play.</p></div>
    </div>
    <div class="hb-settings">
      <div class="hb-setting">
        <p class="hb-setting-name" id="peek-lbl">Edge that shows</p>
        <div class="seg" id="peek-seg" role="group" aria-labelledby="peek-lbl">
          <button type="button" data-peek="0" aria-pressed="false">None</button>
          <button type="button" data-peek="8" aria-pressed="false">Small</button>
          <button type="button" data-peek="14" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-peek="20" aria-pressed="false">Large</button>
        </div>
        <p class="hb-hint">The strip of each card left showing above the next.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="shrink-lbl">How much cards shrink</p>
        <div class="seg" id="shrink-seg" role="group" aria-labelledby="shrink-lbl">
          <button type="button" data-step="0.05" aria-pressed="false">A little</button>
          <button type="button" data-step="0.10" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-step="0.12" aria-pressed="false">A lot</button>
        </div>
        <p class="hb-hint">Covered cards shrink so the deck looks deep.</p>
      </div>
    </div>
    <details class="hb-options">
      <summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
      <div class="hb-settings">
        <div class="hb-setting">
          <p class="hb-setting-name" id="count-lbl">Number of cards</p>
          <div class="seg" id="count-seg" role="group" aria-labelledby="count-lbl">
            <button type="button" data-count="3" aria-pressed="false">3</button>
            <button type="button" data-count="5" class="on" aria-pressed="true">5</button>
            <button type="button" data-count="7" aria-pressed="false">7</button>
          </div>
          <p class="hb-hint">More cards make a taller deck and a longer scroll.</p>
        </div>
      </div>
    </details>
  </section>

  <section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">3</span>
      <div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
    </div>
    <div class="hb-card">
      <p class="hb-prompt">Add stacking cards to [your set of project or step cards]. Make each card stick to the top of the scrolling area so the next card slides up over it, and push each later card down by the offset in the settings so a strip of the cards underneath stays visible, like a deck. As a card is covered, shrink it slightly from its top edge, so buried cards look farther away. Leave some room after the last card so the finished deck stays on screen. Use scroll-driven animations where the browser supports them, with a small script as the fallback. If the visitor has reduced motion turned on, let the cards stack without shrinking. Match the settings listed below.</p>
      <div class="hb-chips-box" hidden>
        <p class="hb-chips-title">Your settings</p>
        <ul class="hb-chips"></ul>
      </div>
      <div class="hb-copy-row">
        <button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
        <p class="hb-hint">Replace the words in brackets with your own element. Your settings are added at the end.</p>
      </div>
    </div>
    <div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
  </section>

  <section class="hb-about" aria-labelledby="hb-what-title">
    <div class="hb-what">
      <h2 id="hb-what-title">What it is</h2>
      <div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
    </div>
    <div class="hb-fit">
      <h2>Good for</h2>
      <ul class="hb-tags hb-good"><li>Portfolios</li><li>Case studies</li><li>Onboarding steps</li><li>Feature tours</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Long text</li><li>Many cards</li></ul>
    </div>
  </section>

  <section class="hb-related" aria-labelledby="hb-related-title" hidden>
    <h2 id="hb-related-title">Similar animations</h2>
    <div class="hb-rel-list"></div>
  </section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
  const ALL_CARDS=[
    {num:'01',title:'Harbor House', sub:'Architecture',body:'A timber home on the edge of the water.',      ac:'#aa632b',vis:'linear-gradient(135deg,#f5ede0,#e8d0a8)'},
    {num:'02',title:'Night Market', sub:'Photography', body:'Forty evenings of food stalls and lanterns.',  ac:'#37835b',vis:'linear-gradient(135deg,#d4ede2,#a8d8bc)'},
    {num:'03',title:'Field Notes',  sub:'Journal',     body:'Small drawings from a year of walks.',         ac:'#3a70a8',vis:'linear-gradient(135deg,#ccdff0,#a0c4e4)'},
    {num:'04',title:'Slow Roast',   sub:'Brand',       body:'A new look for a family coffee roaster.',      ac:'#90701e',vis:'linear-gradient(135deg,#f0e8c0,#e0d098)'},
    {num:'05',title:'North Line',   sub:'Maps',        body:'A clearer map for a busy train network.',      ac:'#548034',vis:'linear-gradient(135deg,#d4e8c0,#b0d490)'},
    {num:'06',title:'Open Studio',  sub:'Workshop',    body:'Two days of making things by hand.',           ac:'#8a3a68',vis:'linear-gradient(135deg,#f0d0e4,#e0a8c8)'},
    {num:'07',title:'Tide Tables',  sub:'App',         body:'Daily tides for every beach on the coast.',    ac:'#3a5aa0',vis:'linear-gradient(135deg,#ccd4f0,#a0b0e8)'},
  ];
  const stage=document.getElementById('stage'),cardsEl=document.getElementById('cards');
  const supportsSDCA=CSS.supports('animation-timeline','scroll()');
  const motionMQ=window.matchMedia('(prefers-reduced-motion: reduce)');
  let numCards=5,scaleStep=0.10,peekPx=14,useJsFallback=!supportsSDCA,ticking=false,currentCards=[];
  let contents=[],cardsTop=0,cardsH=1,lastScales=[];
  const lay=document.getElementById('lay'),ticksEl=document.getElementById('ticks'),copyEl=document.getElementById('copy');
  const capFull=document.getElementById('cap-full'),notes=document.querySelectorAll('.hb-mode-notes p');
  let mode='normal',ticks=[],lit=[],cov=[],tops=[];

  const face=d=>`<div class="card__content" style="--ac:${d.ac}">
        <div class="card__text">
          <div class="card-num" aria-hidden="true">${d.num}</div>
          <div class="card-title">${d.title}</div>
          <div class="card-sub">${d.sub}</div>
          <div class="card-body">${d.body}</div>
          <div class="card-btn" aria-hidden="true">View project →</div>
        </div>
        <div class="card__visual" style="background:${d.vis}"></div></div>`;

  function buildCards(){
    cardsEl.innerHTML='';cardsEl.style.setProperty('--numcards',numCards);currentCards=[];
    ALL_CARDS.slice(0,numCards).forEach((d,i)=>{
      const el=document.createElement('div');
      el.className='card';el.style.setProperty('--index',i+1);
      el.innerHTML=face(d);
      cardsEl.appendChild(el);currentCards.push(el);
    });
    // the plain list for Compare and the comb for See inside are rebuilt with the cards, from the same count
    copyEl.innerHTML='';copyEl.style.setProperty('--numcards',numCards);
    ticksEl.innerHTML='';lay.style.setProperty('--n',numCards);lit=[];cov=[];
    ALL_CARDS.slice(0,numCards).forEach((d,i)=>{
      const c=document.createElement('div');c.innerHTML=face(d);copyEl.appendChild(c.firstChild);
      const t=document.createElement('i');t.className='tick';t.style.setProperty('--i',i);ticksEl.appendChild(t);
    });
    ticks=[...ticksEl.children];
    // run-out lives inside #cards so the last card can stay pinned to the end
    const runOut=document.createElement('div');runOut.className='run-out';
    cardsEl.appendChild(runOut);
    contents=currentCards.map(c=>c.querySelector('.card__content'));
    lastScales=currentCards.map(()=>-1);
    cardsEl.classList.toggle('js-fallback',useJsFallback);
    measure();requestAnimationFrame(update);
  }

  const lerp=(a,b,t)=>a+(b-a)*t,clamp=(v,a,b)=>Math.min(Math.max(v,a),b);

  /* Geometry, measured once instead of per frame. #cards itself is static, so its rect is a reliable
     origin: a sticky card's offsetTop reports where it is currently stuck, which changes as you scroll. */
  function measure(){
    cardsTop=cardsEl.getBoundingClientRect().top-stage.getBoundingClientRect().top-stage.clientTop+stage.scrollTop;
    cardsH=Math.max(1,cardsEl.offsetHeight);
    // A card is the box less its 12px foot and the strips above the deepest one; on the shortest cards the one-line text hides
    const short=stage.clientHeight-12-(numCards-1)*peekPx<170;
    cardsEl.classList.toggle('short',short);copyEl.classList.toggle('short',short);
    // where each card sticks: the scroll at which its box reaches the top
    let y=cardsTop;tops=currentCards.map(c=>{const t=y;y+=c.offsetHeight;return t});
  }

  function update(){
    if(useJsFallback&&!motionMQ.matches){
      // Mirrors the CSS exit-crossing timeline: 0 when #cards' top edge reaches the
      // stage top, 1 when its bottom edge does. Card i owns the slice [i/N,(i+1)/N].
      const N=currentCards.length,p=clamp((stage.scrollTop-cardsTop)/cardsH,0,1);
      for(let i=0;i<N;i++){
        const t=clamp(p*N-i,0,1),ri=N-i;
        const s=+lerp(1,1+scaleStep-scaleStep*ri,t).toFixed(4);
        if(s!==lastScales[i]){contents[i].style.transform=`scale(${s})`;lastScales[i]=s}
      }
    }
    // See inside: a comb line is bright once its card is stuck
    // and a card shows its outline once the next one lies on it
    if(mode==='inside'){
      const y=stage.scrollTop+1;
      ticks.forEach((t,i)=>{const on=y>=tops[i];if(on!==lit[i]){t.classList.toggle('on',on);lit[i]=on}});
      currentCards.forEach((c,i)=>{const on=i<tops.length-1&&y>=tops[i+1];if(on!==cov[i]){c.classList.toggle('covered',on);cov[i]=on}});
    }
    ticking=false;
  }

  // The notes: the markup's own words for the default, other words for no edge and for reduced motion
  const WORDS=[...notes].map(n=>n.textContent);
  const NOTES={
    inside0:'Inside, with no edge showing every card stops on the same line and hides the last; outlines show each card\'s full size as it is covered. Scroll the box or press Play to watch.',
    compare0:'In Scroll past, cards go by like a plain list; in Stack up, each sticks at the top and the next slides over it and hides it. Scroll the box or press Play to watch.',
    stillIn:'Shown without shrinking: the dashed lines mark where each card stops, a strip lower than the last; the inner outlines show how small each covered card would get.',
    stillIn0:'Shown without shrinking: with no edge showing, every card stops on the same line, and the next one hides the last completely.',
    stillCmp:'Without shrinking: in Scroll past, cards go by like a plain list; in Stack up, each sticks at the top and the next slides over it. Scroll the box or press Play to watch.',
    stillCmp0:'Without shrinking: in Scroll past, cards go by like a list; in Stack up, each sticks and the next slides over and hides it. Scroll the box or press Play to watch.'
  };
  function describe(){
    const rm=motionMQ.matches,none=peekPx===0;
    notes[0].textContent=rm?(none?NOTES.stillIn0:NOTES.stillIn):(none?NOTES.inside0:WORDS[0]);
    notes[1].textContent=rm?(none?NOTES.stillCmp0:NOTES.stillCmp):(none?NOTES.compare0:WORDS[1]);
    capFull.textContent=rm?'How small it would get':'Full size before it shrank';
  }
  const LABELS={normal:stage.getAttribute('aria-label'),inside:'The stack of cards with a line where each card stops and the full size of each covered card',
    compare:'The cards twice: scrolling past as a plain list, and stacking into a deck'};
  document.addEventListener('hb:mode',e=>{
    mode=e.detail.mode;stage.setAttribute('aria-label',LABELS[mode]);
    ticks.forEach(t=>t.classList.remove('on'));lit=[];cov=[];update();
  });

  stage.addEventListener('scroll',()=>{if(!ticking){requestAnimationFrame(update);ticking=true}},{passive:true});
  let rt;addEventListener('resize',()=>{clearTimeout(rt);rt=setTimeout(()=>{measure();update()},150)});
  // switching reduced motion on must clear the fallback's inline scales, or they would sit frozen on the cards
  motionMQ.addEventListener('change',()=>{describe();contents.forEach(c=>c.style.removeProperty('transform'));lastScales=lastScales.map(()=>-1);update()});

  function choices(id,pick){
    const buttons=document.querySelectorAll('#'+id+' button');
    buttons.forEach(b=>b.addEventListener('click',()=>{
      buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
      pick(b.dataset);
    }));
  }
  choices('peek-seg',d=>{
    peekPx=+d.peek;document.documentElement.style.setProperty('--peek',peekPx+'px');
    describe();measure();update();          // peek changes each card's height, so geometry moves
  });
  choices('shrink-seg',d=>{
    scaleStep=+d.step;document.documentElement.style.setProperty('--scale-step',scaleStep);
    lastScales=lastScales.map(()=>-1);update();
  });
  choices('count-seg',d=>{numCards=+d.count;buildCards()});
  describe();buildCards();
</script>
</body>
</html>