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.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
fix(stacking-cards): correct the scroll geometry, repair the JS fallback, sync docs
matin548562c7a613
diff --git a/animations/01-scroll-based/stacking-cards/README.md b/animations/01-scroll-based/stacking-cards/README.mdindex 4a2816a9..c389348e 100644--- a/animations/01-scroll-based/stacking-cards/README.md+++ b/animations/01-scroll-based/stacking-cards/README.md@@ -4,7 +4,7 @@## What it is-A set of cards that stack on top of each other as the user scrolls. Each card is roughly viewport-height tall and uses `position: sticky` to pin itself to the top of the scroll container. As subsequent cards scroll up, they layer over the previous ones, building a literal physical stack. Subtle depth cues — scale reduction, brightness dimming, and a small downward shift — reinforce the sense that buried cards are physically behind the topmost one.+A set of cards that stack on top of each other as the user scrolls. Each card uses `position: sticky` to pin itself to the top of the scroll container, so later cards layer over earlier ones and build a literal physical stack. A CSS scroll-driven timeline shrinks each buried card as it is covered, and a per-index `padding-top` leaves the previous card's top edge peeking above the next — the tab that makes the pile read as a deck rather than a single card.## When to use it@@ -15,45 +15,62 @@ A set of cards that stack on top of each other as the user scrolls. Each card is## How it works-The stacking itself requires only CSS. Each card is `position: sticky; top: 0` inside a tall container. The browser keeps each card at the top of the viewport until the next one scrolls past it. Cards are layered using `z-index` so later cards render on top.+The stacking itself needs no JavaScript at all. Sticky goes on the `.card` wrapper — not on the inner content — and a per-index `padding-top` pushes each card's content lower, so the card above it stays visible as a peek tab.```css.card {position: sticky;top: 0;- height: 600px;- z-index: var(--card-index); /* increases per card */+ padding-top: calc(var(--index0) * var(--peek)); /* the peek tab */+ z-index: var(--index); /* later cards on top */}```-JavaScript computes the depth of each card — how many cards are stacked on top of it — and applies visual cues proportionally:+The depth cue comes from a CSS scroll-driven animation. `#cards` declares a view timeline, and each card animates over its own slice of that timeline: card *i* of *N* scales during `[i/N, (i+1)/N]` of the exit phase, so the cards compress one after another rather than all at once.-```js-const cardH = 600;-const topmost = Math.min(Math.floor(scrollTop / cardH), cards.length - 1);-const depth = Math.max(0, topmost - cardIndex);-const t = depth / (cards.length - 1); // 0 = surface, 1 = deepest+```css+#cards { view-timeline-name: --cards-timeline; }++.card__content {+ animation: card-scale linear both;+ animation-timeline: --cards-timeline;+ animation-range: exit-crossing calc(var(--index0) / var(--numcards) * 100%)+ exit-crossing calc(var(--index) / var(--numcards) * 100%);+ transform-origin: 50% 0%; /* collapse downward, keeping the peek tab flush */+}+@keyframes card-scale {+ to { transform: scale(calc(1 + var(--scale-step) - var(--scale-step) * var(--reverse-index))); }+}+```++Reverse-index is what makes the depth read correctly: the topmost card (reverse-index 1) lands at scale 1.0, and each card buried under it compresses one step further.-card.style.transform = `translateY(${depth * 5}px) scale(${lerp(1, SCALE_FLOOR, t)})`;-card.style.filter = `brightness(${lerp(1, BRIGHT_FLOOR, t)})`;+For browsers without `animation-timeline`, a `requestAnimationFrame` handler reproduces the same curve. Progress runs from 0 when the deck's top edge reaches the container top to 1 when its bottom edge does, and each card takes the same `[i/N, (i+1)/N]` slice:++```js+const p = clamp((stage.scrollTop - cardsTop) / cardsH, 0, 1);+const t = clamp(p * N - i, 0, 1);+content.style.transform = `scale(${lerp(1, 1 + step - step * (N - i), t)})`;```## Key parameters| Parameter | Default | Effect ||-----------|---------|--------|-| Scale floor | 0.94 | Minimum scale for buried cards; lower = more pronounced depth |-| Brightness floor | 0.85 | Minimum brightness for buried cards; lower = darker depth shadow |-| Card height | 600px | Must match `height` in CSS for correct depth calculation |-| Translate per depth | 5px | Downward shift per depth level; creates a sinking sensation |+| `--scale-step` | 0.10 | Scale lost per level of depth; higher = a more pronounced deck |+| `--peek` | 14px | Per-index `padding-top`; the height of each card's visible tab |+| Card count | 5 | Cards in the deck (3–7); also the `N` that divides the timeline |+| `--stage-h` | 620px / 480px mobile | Scroll container height; card content is this minus 80px |## Production notes-- **CSS does the work; JS adds polish.** The stacking is correct with zero JavaScript — cards appear in the right order purely from `position: sticky` and `z-index`. JavaScript is only needed for the depth cues (scale, brightness). Set both sliders to their max values to see the CSS-only version.-- **Animating `filter: brightness()` is GPU-composited.** It does not trigger layout or paint. Scale via `transform` is equally safe. Both are compositor-only properties.-- **Card height must be consistent.** The depth calculation uses a fixed card height. If cards have varying heights, compute `offsetTop` from the DOM rather than multiplying by a constant.-- **GSAP ScrollTrigger** with `pin: true` on each card and a `scrub` timeline can drive the same scale/brightness cues with more per-card easing control. Framer Motion's `useScroll` + `useTransform` achieves the same in React with viewport-relative progress per element.-- **Accessibility.** The scale and brightness changes are subtle and unlikely to trigger vestibular discomfort. Under `prefers-reduced-motion: reduce`, disable the depth cues entirely — the stacking still reads clearly from z-order alone.+- **CSS does the work; JS adds polish.** The stacking is correct with zero JavaScript — cards appear in the right order purely from `position: sticky` and `z-index`. The scroll-driven timeline supplies the depth cue (scale), and the JavaScript path exists only for browsers without `animation-timeline`.+- **`transform: scale()` is compositor-only.** It triggers neither layout nor paint, which is why the depth cue stays cheap even with every card animating at once.+- **Never read `offsetTop` from a sticky element.** This is the trap in this pattern. `position: sticky` changes an element's *used* position, so `offsetTop` reports where the card is currently stuck, not where it sits in flow — the value moves as you scroll, and a measurement taken mid-scroll comes back with offsets that run backwards. Accumulate `offsetHeight` instead (sticky does not affect it), and take the container's origin from a non-sticky ancestor.+- **Watch the coordinate space.** `offsetTop` is measured from the nearest positioned ancestor — usually `body` — while `scrollTop` is measured from the scroll container's content origin. Mixing them silently offsets everything by the page chrome above the container. If a parent and child share an `offsetParent`, adding their `offsetTop`s double-counts.+- **Keep the fallback honest.** A JS fallback that merely "looks about right" is worse than none, because nobody re-checks it. Diff its output against the native timeline at several scroll positions — here the two agree to within rounding at every point.+- **GSAP ScrollTrigger** with `pin: true` on each card and a `scrub` timeline can drive the same scale cue with more per-card easing control. Framer Motion's `useScroll` + `useTransform` achieves the same in React with viewport-relative progress per element.+- **Accessibility.** The scale change is subtle and unlikely to trigger vestibular discomfort. Under `prefers-reduced-motion: reduce`, disable the depth cue entirely — the stacking still reads clearly from z-order alone. Gate *both* paths: killing the CSS animation does nothing about a JavaScript fallback that keeps writing inline transforms, and any inline transform already set must be cleared or it will sit frozen on top of the CSS timeline.## See alsodiff --git a/animations/01-scroll-based/stacking-cards/index.html b/animations/01-scroll-based/stacking-cards/index.htmlindex 3c49612a..eed643d0 100644--- a/animations/01-scroll-based/stacking-cards/index.html+++ b/animations/01-scroll-based/stacking-cards/index.html@@ -164,7 +164,9 @@ body{padding-top:46px}const cardsSl=document.getElementById('cards-sl'),cardsValEl=document.getElementById('cards-val');const debugTog=document.getElementById('debug-tog'),jsTog=document.getElementById('js-tog');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=[],cardOffsets=[],cardsTop=0,cardsH=1,maxScroll=1,lastScales=[],lastProg='',lastTop='';if(!supportsSDCA){jsTog.checked=true}function buildCards(){@@ -185,26 +187,46 @@ body{padding-top:46px}<div class="card__visual" style="background:${d.vis}"></div></div>`;cardsEl.appendChild(el);currentCards.push(el);});+ contents=currentCards.map(c=>c.querySelector('.card__content'));+ lastScales=currentCards.map(()=>-1);cardsEl.classList.toggle('js-fallback',useJsFallback);- requestAnimationFrame(update);+ 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.+ Do NOT use card.offsetTop here: .card is position:sticky, so offsetTop reports+ where the card is *currently stuck*, which changes as you scroll — measuring+ mid-scroll yielded offsets that ran backwards. offsetHeight is unaffected by+ sticky, so accumulating heights gives each card's static offset at any scroll.+ #cards itself is static, so its rect is a reliable origin. */+ function measure(){+ cardsTop=Math.round(cardsEl.getBoundingClientRect().top-stage.getBoundingClientRect().top+stage.scrollTop);+ cardsH=Math.max(1,cardsEl.offsetHeight);+ maxScroll=Math.max(1,stage.scrollHeight-stage.clientHeight);+ let acc=0;+ cardOffsets=currentCards.map(c=>{const o=acc;acc+=c.offsetHeight;return o});+ }+function update(){- const st=stage.scrollTop,max=stage.scrollHeight-stage.clientHeight,stageH=stage.clientHeight;- scrollProg.textContent=max>0?Math.round(st/max*100)+'%':'0%';- const cardsTop=cardsEl.offsetTop;+ const st=stage.scrollTop;+ const prog=Math.round(st/maxScroll*100)+'%';+ if(prog!==lastProg){scrollProg.textContent=prog;lastProg=prog}+ // topmost = the last card whose sticky top has reached the stage toplet top=0;- currentCards.forEach((c,i)=>{if(st>=cardsTop+c.offsetTop-stageH*0.4)top=i});- topmostEl.textContent=ALL_CARDS[top].num;- if(useJsFallback){- const cardsH=cardsEl.offsetHeight,N=currentCards.length;- const exitProgress=clamp((st-(cardsTop+cardsH-stageH))/cardsH,0,1);- currentCards.forEach((c,i)=>{- const ri=N-i,t=clamp((exitProgress-i/N)/((i+1)/N-i/N),0,1);- c.querySelector('.card__content').style.transform=`scale(${lerp(1,1+scaleStep-scaleStep*ri,t).toFixed(4)})`;- });+ for(let i=0;i<cardOffsets.length;i++) if(st>=cardsTop+cardOffsets[i]) top=i;+ const num=ALL_CARDS[top].num;+ if(num!==lastTop){topmostEl.textContent=num;lastTop=num}+ 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((st-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}+ }}ticking=false;}@@ -212,21 +234,27 @@ body{padding-top:46px}stage.addEventListener('scroll',()=>{if(!ticking){requestAnimationFrame(update);ticking=true}},{passive:true});scaleSl.addEventListener('input',()=>{scaleStep=scaleSl.value/100;scaleValEl.textContent=scaleStep.toFixed(2);- document.documentElement.style.setProperty('--scale-step',scaleStep);update();+ document.documentElement.style.setProperty('--scale-step',scaleStep);+ lastScales=lastScales.map(()=>-1);update();});peekSl.addEventListener('input',()=>{peekPx=+peekSl.value;peekValEl.textContent=peekPx+'px';- document.documentElement.style.setProperty('--peek',peekPx+'px');update();+ document.documentElement.style.setProperty('--peek',peekPx+'px');+ measure();update(); // peek changes each card's height, so geometry moves});+ let rt;addEventListener('resize',()=>{clearTimeout(rt);rt=setTimeout(()=>{measure();update()},150)});cardsSl.addEventListener('input',()=>{numCards=+cardsSl.value;cardsValEl.textContent=numCards;buildCards()});debugTog.addEventListener('change',()=>document.querySelectorAll('.debug-badge').forEach(b=>b.classList.toggle('on',debugTog.checked)));jsTog.addEventListener('change',()=>{useJsFallback=jsTog.checked||!supportsSDCA;cardsEl.classList.toggle('js-fallback',useJsFallback);- if(!useJsFallback)currentCards.forEach(c=>c.querySelector('.card__content').style.removeProperty('transform'));- update();+ // leaving the fallback (or honouring reduced motion) must clear the inline+ // transforms, or a stale scale would sit on top of the CSS timeline+ if(!useJsFallback||motionMQ.matches)contents.forEach(c=>c.style.removeProperty('transform'));+ lastScales=lastScales.map(()=>-1);+ measure();update();});- document.getElementById('reset-btn').addEventListener('click',()=>{stage.scrollTop=0;update()});+ document.getElementById('reset-btn').addEventListener('click',()=>{stage.scrollTop=0;measure();update()});document.documentElement.style.setProperty('--scale-step',scaleStep);buildCards();</script>