中文
作品
Scroll · Vanilla JS + CSS

Stacking cards

卡片滚动堆叠

Stack cards on top of each other as the page scrolls.

Also searched as: 滑动时卡片一张压着一张叠起来, 作品集卡片往下滑时堆叠, 卡片粘在顶上被下一张盖住, 滚动时后一张卡压住前一张

AI Markdown (.md)
Placement
Card list
Mood
Refined, Crisp
Trigger
Scroll
Site types
作品集, 个人网站

How it works & accessibility

Make each card position: sticky with a staggered top, then scale the covered card down from its top edge according to how close the next card has come, updating at most once per frame while scrolling; with reduced motion there is no scaling and without JavaScript the cards still stack.

Best for: Card list (Scroll).

Reduced motion: 不缩放;卡片照样贴在顶上一张盖一张(那是浏览器自己的滚动,不是动画)

Mobile & touch: 和桌面一样;手机上卡片别太高,一张最好不超过屏幕高的七成

Key parameters

ParameterKeyDefaultRangeNotes
叠起来时露出的边offset16px——
被盖住的卡缩到多少scale0.94倍——

Ready-to-paste AI prompt

Add “Stacking cards” to the card list in my project: Make each card position: sticky with a staggered top, then scale the covered card down from its top edge according to how close the next card has come, updating at most once per frame while scrolling; with reduced motion there is no scaling and without JavaScript the cards still stack.
Parameters: offset: 16px, scale: 0.94×.
Preserve existing content and layout. Respect prefers-reduced-motion by showing the final state. Content must remain visible if JavaScript fails or is disabled.
Reference: https://donglang.linter.top/effects/stacking-cards.md (canonical specification and reference code).

Dependency-free reference code

CSS
/* 卡片滚动堆叠的样式,配合 stacking-cards.js。给卡片列表加 class="sc-list",每张卡是它的直接子元素。
   卡是 position: sticky,按上边缩放(transform-origin 在上边,缩放不改变卡的上边位置)。脚本按第几张写错开的 top;
   没有脚本时每张卡都贴在 --sc-top(默认 24px),照样一张盖一张。列表的祖先不能有 overflow: hidden,不然 sticky 会失效。 */
/* 默认值写在 :where() 里(不占优先级):网站自己在 .sc-list 上改的 --sc-top,不管写在这段代码前面还是后面,都用网站自己的 */
:where(.sc-list) {
  --sc-top: 24px;
}
.sc-list > * {
  position: sticky;
  top: var(--sc-top);
  transform-origin: 50% 0;
}
JavaScript
// 卡片滚动堆叠(Stacking cards)· 原生 JS,不依赖任何库。
// 参考 Animation Handbook 的 stacking-cards 的做法(MIT),自己实现,没有复制代码。
// 用法:stackCards(列表),返回 { update(), destroy() }。列表的每个子元素是一张卡(配合 stacking-cards.css:卡是 position: sticky、按上边缩放)。
// 假设每张卡一样高(offset 比卡高还大时,每一张只有盖住、没盖住两种样子,没有渐变);列表的祖先不能有 overflow: hidden(会让 sticky 失效)。
// 卡要自己有不透明的底色,不然盖在下面的卡的字会从上面那张里透出来;卡上不要写 transition: all(会让缩放慢半拍);装上以后新加进列表的卡不归它管。
// 第 i 张卡(从 0 起)贴在离顶 top + i × offset 处:往下滑时每张卡先贴在自己的位置,下一张从下面滑上来盖住它,相邻两张露出 offset 的边。
// 被盖住的程度 q = clamp((这一张的上边 + 卡高 − 下一张的上边) / (卡高 − offset), 0, 1);这一张缩到 1 − (1 − scale) × q(scale 属性,按上边缩放,
// 不碰卡原来的 transform);最后一张从不缩放。
// 选项:top 第一张离顶多远(px,默认 24);offset 露出的边(px,默认 16);scale 被盖住的卡最后缩到多少(默认 0.94);
// root 滚动的容器,默认整个页面(window),放在自己会滚动的框里时传那个框(top 就是离那个框的顶)。
// 滚动(passive)里只排一次逐帧更新;改窗口大小、列表或滚动框自己变大小时重算;update() 手动重算。
// 开启"减少动态"时:不监听滚动、不排逐帧更新,不缩放(错开的 top 照写,卡片照样 sticky 地叠——那是浏览器自己的滚动行为);
// ignoreReducedMotion 只给演示强制播放用。没有脚本时:卡都贴在 --sc-top(默认 24px),照样一张盖一张,只是没有露边和缩放,内容完整。
// destroy():摘监听、取消排好的逐帧更新、还原每张卡行内的 top、scale,之后 update() 什么都不做;对同一个列表重复调用,先 destroy 旧的。

// 每个列表现在装着的控制对象(对同一个列表重复调用时先拆旧的)
const prevs = new WeakMap();

export function stackCards(list, {
  top = 24,
  offset = 16,
  scale = 0.94,
  root = window,
  ignoreReducedMotion = false,
} = {}) {
  prevs.get(list)?.destroy();
  const reduce = !ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches;
  const cards = [...list.children].filter((el) => el instanceof HTMLElement).map((el) => ({ el, top: el.style.top, scale: el.style.scale }));
  cards.forEach(({ el }, i) => { el.style.top = `${top + i * offset}px`; });
  let dead = false;
  let frame = 0;

  const update = () => {
    if (dead || reduce) return;
    const tops = cards.map(({ el }) => el.getBoundingClientRect().top);
    cards.forEach(({ el }, i) => {
      if (i === cards.length - 1) { el.style.scale = ''; return; }
      const h = el.offsetHeight;
      const room = h - offset;
      const q = room > 0 ? Math.min(1, Math.max(0, (tops[i] + h - tops[i + 1]) / room)) : (tops[i + 1] <= tops[i] + h ? 1 : 0);
      const s = 1 - (1 - scale) * q;
      el.style.scale = s >= 1 ? '' : s.toFixed(4);
    });
  };
  const schedule = () => {
    if (dead || frame) return;
    frame = requestAnimationFrame(() => { frame = 0; update(); });
  };
  let resized = null;
  if (!reduce) {
    root.addEventListener('scroll', schedule, { passive: true });
    window.addEventListener('resize', schedule, { passive: true });
    resized = new ResizeObserver(schedule);
    resized.observe(list);
    if (root !== window) resized.observe(root);
    update();
  }

  const ctl = {
    update,
    destroy() {
      if (dead) return;
      dead = true;
      cancelAnimationFrame(frame);
      frame = 0;
      if (resized) {
        root.removeEventListener('scroll', schedule);
        window.removeEventListener('resize', schedule);
        resized.disconnect();
      }
      cards.forEach(({ el, top: t, scale: s }) => { el.style.top = t; el.style.scale = s; });
      if (prevs.get(list) === ctl) prevs.delete(list);
    },
  };
  prevs.set(list, ctl);
  return ctl;
}
HTML
<!-- 卡片滚动堆叠:每张卡一样高,一张张往下排;列表的祖先不能有 overflow: hidden。没有脚本时卡照样贴在顶上一张盖一张 -->
<section class="sc-list" id="works">
  <article class="work">海边的周末</article>
  <article class="work">城市夜跑</article>
  <article class="work">一本旧书</article>
  <article class="work">雨天的咖啡馆</article>
</section>
<script type="module">
  import { stackCards } from './stacking-cards.js';
  stackCards(document.getElementById('works'), { top: 24, offset: 16, scale: 0.94 });
</script>

Shown once per release · Always available in changelog