Scrolling Gallery
A zig-zag column of pictures that slide past each other as you scroll.
Customize
<ScrollingGallery images={images} />Changes show live and stay in the address, so a link keeps them.
Code
"use client";
import { useRef } from "react";
import { gsap } from "gsap";
import { useGSAP } from "@gsap/react";
// A zig-zag column of pictures that slide past each other as you scroll. Every picture has its own
// speed: a fast one climbs the screen quicker than the page scrolls, a slow one lags behind, so
// neighbours overlap and part again. A quick scroll also leans the pictures over (skew).
//
// It does NOT take over the page's scroll. The page scrolls natively; we only read where it is and
// nudge each picture with a transform. The nudge is computed from the picture's own position, so
// a picture sits exactly where the layout puts it when it is level with the middle of the screen
// and drifts away from that spot as it travels. Pictures that are already on screen when the page
// loads start at rest, so the first screen looks the way the layout was drawn.
export type ScrollingGalleryImage = {
/** The image address. */
src: string;
/** Alt text for the picture. Use an empty string for a purely decorative one. */
alt: string;
/** How fast this picture travels compared with the scroll. 1 moves with the page, above 1 climbs quicker, below 1 lags behind. */
speed?: number;
};
export type ScrollingGalleryProps = {
/** The pictures, top to bottom. */
images: ScrollingGalleryImage[];
/** How strongly the pictures drift from their spot. 0 turns the parallax off, 1 is each picture's own speed, 2 doubles it. */
parallax?: number;
/** The most a picture leans, in degrees, when the page scrolls fast. 0 never leans. */
skew?: number;
/** How long a picture takes to catch up with the scroll, in seconds. A little lag feels soft. 0 follows the scroll exactly. */
smoothing?: number;
/** Width of each picture as a percent of the gallery. On a phone-wide gallery it grows to about half so the pictures stay big, and it never gets too wide for the zig-zag to fit. */
size?: number;
/** How far apart the left and right pictures sit, as a percent of a picture's width. 0 stacks them in one column. */
stagger?: number;
/** Space between the pictures in the column, in pixels. */
gap?: number;
/** Width divided by height of each picture. 1 is square, 0.8 is a 4:5 portrait. */
aspectRatio?: number;
/** The element that scrolls, or a selector for it. Leave it out to follow the window. */
scroller?: HTMLElement | string | null;
/** An id for the outer box. */
id?: string;
/** Extra classes for the outer box. */
className?: string;
/** Extra classes for each picture, e.g. a radius or a shadow. */
imageClassName?: string;
};
function resolveScroller(scroller: ScrollingGalleryProps["scroller"]): HTMLElement | null {
if (!scroller) return null;
if (typeof scroller === "string") return document.querySelector<HTMLElement>(scroller);
return scroller;
}
const clamp = (min: number, max: number, value: number) => Math.min(max, Math.max(min, value));
export function ScrollingGallery({
images,
parallax = 1,
skew = 8,
smoothing = 0.6,
size = 26,
stagger = 40,
gap = 0,
aspectRatio = 1,
scroller = null,
id,
className = "",
imageClassName = "",
}: ScrollingGalleryProps) {
const rootRef = useRef<HTMLDivElement>(null);
const rowRefs = useRef<(HTMLLIElement | null)[]>([]);
const imageRefs = useRef<(HTMLImageElement | null)[]>([]);
// Read on every frame, so moving these sliders doesn't rebuild anything
const live = useRef({ parallax, skew });
live.current = { parallax, skew };
// The speeds are read when measuring and on every frame, so a changed speed lands without a rebuild
const speeds = useRef<number[]>([]);
speeds.current = images.map((image) => image.speed ?? 1);
useGSAP(
() => {
const root = rootRef.current;
const rows = rowRefs.current.slice(0, images.length).filter((row): row is HTMLLIElement => row !== null);
const pictures = imageRefs.current.slice(0, images.length).filter((image): image is HTMLImageElement => image !== null);
if (!root || rows.length === 0 || rows.length !== pictures.length) return;
// Reduced motion: nothing below runs, the pictures stay where the layout puts them
const mm = gsap.matchMedia();
mm.add("(prefers-reduced-motion: no-preference)", () => {
const scrollElement = resolveScroller(scroller);
const readScroll = () => (scrollElement ? scrollElement.scrollTop : window.scrollY);
// The visible part of whatever scrolls: its top edge and height, in window coordinates
const readView = () => {
if (!scrollElement) return { top: 0, height: window.innerHeight };
return { top: scrollElement.getBoundingClientRect().top, height: scrollElement.clientHeight };
};
const moveY = pictures.map((picture) => gsap.quickTo(picture, "y", { duration: Math.max(smoothing, 0.0001), ease: "power3.out" }));
const lean = gsap.quickTo(pictures, "skewY", { duration: 0.5, ease: "power3.out" });
// Where each row's middle sits in the root, and the distance from the middle of the screen
// at which that row is "at rest" (its drift is zero there). That is the middle of the screen,
// unless the row is already on screen when the page is at the top: then it rests where it starts.
let middles: number[] = [];
let restOffsets: number[] = [];
const measure = () => {
const view = readView();
const rootTop = root.getBoundingClientRect().top;
const scrollTopInContent = rootTop - view.top + readScroll();
middles = rows.map((row) => {
const box = row.getBoundingClientRect();
return box.top - rootTop + box.height / 2;
});
restOffsets = middles.map((middle) => {
const middleAtScrollZero = scrollTopInContent + middle;
const startsOnScreen = middleAtScrollZero >= 0 && middleAtScrollZero <= view.height;
return startsOnScreen ? middleAtScrollZero - view.height / 2 : 0;
});
};
measure();
let lastScroll = readScroll();
let velocity = 0; // pixels per second, smoothed. Positive means scrolling down.
let visible = true;
const tick = (_time: number, deltaMs: number) => {
const dt = Math.min(deltaMs, 50) / 1000;
if (dt <= 0) return;
const scrolled = readScroll();
const rawVelocity = (scrolled - lastScroll) / dt;
lastScroll = scrolled;
// Wheel ticks arrive in bursts, so smooth them
velocity += (rawVelocity - velocity) * (1 - Math.exp(-dt * 10));
if (!visible) return;
const { parallax: strength, skew: maxSkew } = live.current;
const view = readView();
const rootTop = root.getBoundingClientRect().top - view.top;
rows.forEach((_, index) => {
const fromMiddle = rootTop + middles[index]! - view.height / 2 - restOffsets[index]!;
// Bounded, so a picture far away never flies off
const travelled = clamp(-view.height, view.height, fromMiddle);
moveY[index]!(((speeds.current[index] ?? 1) - 1) * strength * travelled);
});
// Scrolling down leans the pictures one way, up the other. About 900px a second leans fully.
lean(clamp(-maxSkew, maxSkew, (-velocity / 900) * maxSkew));
};
gsap.ticker.add(tick);
// The gallery changing size (a resize, a new gap or size) moves every row, so measure again
const resizeObserver = new ResizeObserver(measure);
resizeObserver.observe(root);
window.addEventListener("resize", measure);
// Images and fonts above the gallery can push it down after the first measure
window.addEventListener("load", measure);
// No work while the gallery is off screen
const visibility = new IntersectionObserver(([entry]) => {
visible = entry?.isIntersecting ?? true;
}, { rootMargin: "200px 0px" });
visibility.observe(root);
return () => {
gsap.ticker.remove(tick);
resizeObserver.disconnect();
visibility.disconnect();
window.removeEventListener("resize", measure);
window.removeEventListener("load", measure);
gsap.killTweensOf(pictures);
gsap.set(pictures, { clearProps: "transform" });
};
});
return () => mm.revert();
},
{ scope: rootRef, dependencies: [images.length, scroller, smoothing], revertOnUpdate: true },
);
// The two columns sit `stagger` percent of a picture apart, so each row moves half of that.
// The widest the zig-zag may make a picture is the width at which it still fits the box.
const widest = 100 / (1 + stagger / 100);
// In a box narrower than about 620px the picture grows to roughly half of it (the 4 is how fast
// it ramps up), so phones don't get thumbnails. In a wider box this is 0 and `size` rules.
const phoneFloor = "clamp(0px, calc((620px - 100%) * 4), 52%)";
return (
<div id={id} ref={rootRef} className={`relative w-full overflow-x-clip ${className}`}>
<ul className="m-0 flex list-none flex-col p-0" style={{ rowGap: gap }}>
{images.map((image, index) => (
<li
key={`${index}-${image.src}`}
ref={(row) => {
rowRefs.current[index] = row;
}}
className="flex justify-center"
>
<div className="max-w-full" style={{ width: `min(max(${size}%, 80px, ${phoneFloor}), ${widest}%)`, transform: `translateX(${index % 2 === 0 ? stagger / 2 : -stagger / 2}%)` }}>
<img
ref={(picture) => {
imageRefs.current[index] = picture;
}}
src={image.src}
alt={image.alt}
loading="lazy"
decoding="async"
draggable={false}
className={`block w-full object-cover will-change-transform ${imageClassName}`}
style={{ aspectRatio }}
/>
</div>
</li>
))}
</ul>
</div>
);
}
The component. Installs to components/dimaac/scrolling-gallery.tsx.
Install
With the shadcn CLI
npx shadcn@latest add https://ui.dimaac.com/r/scrolling-gallery.jsonIt adds components/dimaac/scrolling-gallery.tsx and installs what it imports. With the @dimaac namespace in components.json (Docs) it's just npx shadcn@latest add @dimaac/scrolling-gallery.
By hand
npm install gsap @gsap/react- Install the packages it uses: gsap, @gsap/react.
- Copy the component file below into components/dimaac/scrolling-gallery.tsx.
- It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
- Import it with import { ScrollingGallery } from "@/components/dimaac/scrolling-gallery". Give its parent a size: it fills it.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
images (required) | ScrollingGalleryImage[] | - | The pictures, top to bottom. |
parallax | number | 1 | How strongly the pictures drift from their spot. 0 turns the parallax off, 1 is each picture's own speed, 2 doubles it. |
skew | number | 8 | The most a picture leans, in degrees, when the page scrolls fast. 0 never leans. |
smoothing | number | 0.6 | How long a picture takes to catch up with the scroll, in seconds. A little lag feels soft. 0 follows the scroll exactly. |
size | number | 26 | Width of each picture as a percent of the gallery. On a phone-wide gallery it grows to about half so the pictures stay big, and it never gets too wide for the zig-zag to fit. |
stagger | number | 40 | How far apart the left and right pictures sit, as a percent of a picture's width. 0 stacks them in one column. |
gap | number | 0 | Space between the pictures in the column, in pixels. |
aspectRatio | number | 1 | Width divided by height of each picture. 1 is square, 0.8 is a 4:5 portrait. |
scroller | HTMLElement | string | null | null | The element that scrolls, or a selector for it. Leave it out to follow the window. |
id | string | - | An id for the outer box. |
className | string | "" | Extra classes for the outer box. |
imageClassName | string | "" | Extra classes for each picture, e.g. a radius or a shadow. |
Use with AI
Agent prompt
Paste it into Claude Code, Cursor or any coding agent, or open it straight in a chat. It carries your Customize settings.
Add the Scrolling Gallery component (<ScrollingGallery />) from DiMaac UI to this project.
Docs: https://ui.dimaac.com/components/scrolling-gallery
Source and dependencies (shadcn registry JSON): https://ui.dimaac.com/r/scrolling-gallery.json
Install it with:
npx shadcn@latest add https://ui.dimaac.com/r/scrolling-gallery.json
Then use it like this:
import { ScrollingGallery } from "@/components/dimaac/scrolling-gallery";
<ScrollingGallery images={images} />
If the shadcn CLI isn't set up here, fetch the registry JSON above, write files[0].content to components/dimaac/scrolling-gallery.tsx and install gsap, @gsap/react.
It uses Tailwind v4 classes, so make sure Tailwind scans that folder. Give its parent a size: it fills it. Keep light and dark mode working and keep its prefers-reduced-motion fallback.
Full index for agents: https://ui.dimaac.com/llms.txtFiles agents read
- llms.txt
- Every component and how to install it
- scrolling-gallery.md
- This page as Markdown: install, props and the full source
- scrolling-gallery.json
- The shadcn registry item
About
A zig-zag column of square pictures, each with its own speed. Scroll and the quick ones climb faster than the page while the slow ones lag behind, so neighbours overlap and part again; scroll fast and every picture leans over (skew). The page keeps its normal, native scroll: nothing takes it over, nothing is smoothed globally, and it plays well with Lenis or any other scroller (pass scroller to follow a scrolling element instead of the window). The first screen loads at rest, the layout is fluid down to phones, and with reduced motion the pictures simply sit in their zig-zag. Ported from the first DiMaac UI, where it ran on a page-wide ScrollSmoother; this version needs no plugin and rebuilds nothing on resize.
- Installs to
components/dimaac/scrolling-gallery.tsx- Uses
- gsap, @gsap/react
- Tags
- gsap, scroll, parallax, skew, images, gallery
Fashion Portrait with Orange Visor by West Kast on Lummi (Lummi License). Modern Architectural Design by rena on Lummi (Lummi License). Elegant Perfume Bottle by Dona Mara on Lummi (Lummi License). Desert Dunes and Mountain Range by Pablo Stanley on Lummi (Lummi License). Vivid Portrait on Pink by Amino on Lummi (Lummi License). Vibrant Cylindrical Arrangement by SHIHO on Lummi (Lummi License). Moody Solitary Figure by Krystyna on Lummi (Lummi License). Dramatic Coastline Aerial View by Cayetano Gros on Lummi (Lummi License). Glossy Pink Sphere by marisol on Lummi (Lummi License). Avant-Garde Fashion Pose by Semihan Dosunmu on Lummi (Lummi License). Minimalist Stucco Building by Siren Media on Lummi (Lummi License). Poised Portrait by Lloyd Creates on Lummi (Lummi License). Elegant Vase with Dried Flowers by Pablo Stanley on Lummi (Lummi License). Mossy Forest Scene by PZF on Lummi (Lummi License). Reflective Spheres and Books in a Desert Mirage by Mariana Pedroza on Lummi (Lummi License). Modern Fashion Pose by Axel Photography on Lummi (Lummi License).