---
title: Scrolling Gallery
description: A zig-zag column of pictures that slide past each other as you scroll.
category: Gallery
tier: free
url: https://ui.dimaac.com/components/scrolling-gallery
registry: https://ui.dimaac.com/r/scrolling-gallery.json
---

# Scrolling Gallery

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.

## Install

With the shadcn CLI:

```bash
npx shadcn@latest add https://ui.dimaac.com/r/scrolling-gallery.json
pnpm dlx shadcn@latest add https://ui.dimaac.com/r/scrolling-gallery.json
bunx --bun shadcn@latest add https://ui.dimaac.com/r/scrolling-gallery.json
```

With the `@dimaac` namespace in components.json: `npx shadcn@latest add @dimaac/scrolling-gallery`

Dependencies:

```bash
pnpm add gsap @gsap/react
npm install gsap @gsap/react
```

By hand:

1. Install the packages it uses: gsap, @gsap/react.
2. Copy the component file below into components/dimaac/scrolling-gallery.tsx.
3. It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
4. Import it with import { ScrollingGallery } from "@/components/dimaac/scrolling-gallery". Give its parent a size: it fills it.

## Usage

```tsx
import { ScrollingGallery } from "@/components/dimaac/scrolling-gallery";

<ScrollingGallery images={images} />
```

## 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. |

## Credits

- Fashion Portrait with Orange Visor: West Kast, Lummi (https://www.lummi.ai/photo/fashion-portrait-with-orange-visor-damql), Lummi License
- Modern Architectural Design: rena, Lummi (https://www.lummi.ai/photo/modern-architectural-design-aozka), Lummi License
- Elegant Perfume Bottle: Dona Mara, Lummi (https://www.lummi.ai/photo/elegant-perfume-bottle-j5t5p), Lummi License
- Desert Dunes and Mountain Range: Pablo Stanley, Lummi (https://www.lummi.ai/photo/desert-dunes-and-mountain-range-bfczd), Lummi License
- Vivid Portrait on Pink: Amino, Lummi (https://www.lummi.ai/photo/vivid-portrait-on-pink-oxbow), Lummi License
- Vibrant Cylindrical Arrangement: SHIHO, Lummi (https://www.lummi.ai/photo/vibrant-cylindrical-arrangement-pj9pp), Lummi License
- Moody Solitary Figure: Krystyna, Lummi (https://www.lummi.ai/photo/moody-solitary-figure-x1avl), Lummi License
- Dramatic Coastline Aerial View: Cayetano Gros, Lummi (https://www.lummi.ai/photo/dramatic-coastline-aerial-view-jml-7), Lummi License
- Glossy Pink Sphere: marisol, Lummi (https://www.lummi.ai/photo/glossy-pink-sphere-45si5), Lummi License
- Avant-Garde Fashion Pose: Semihan Dosunmu, Lummi (https://www.lummi.ai/photo/avant-garde-fashion-pose-1yqoo), Lummi License
- Minimalist Stucco Building: Siren Media, Lummi (https://www.lummi.ai/photo/minimalist-stucco-building-gurez), Lummi License
- Poised Portrait: Lloyd Creates, Lummi (https://www.lummi.ai/photo/poised-portrait-ooi9b), Lummi License
- Elegant Vase with Dried Flowers: Pablo Stanley, Lummi (https://www.lummi.ai/photo/elegant-vase-with-dried-flowers-dhxnk), Lummi License
- Mossy Forest Scene: PZF, Lummi (https://www.lummi.ai/photo/mossy-forest-scene-o4b8t), Lummi License
- Reflective Spheres and Books in a Desert Mirage: Mariana Pedroza, Lummi (https://www.lummi.ai/photo/reflective-spheres-and-books-in-a-modern-setting-U_hc_), Lummi License
- Modern Fashion Pose: Axel Photography, Lummi (https://www.lummi.ai/photo/modern-fashion-pose-zsdav), Lummi License

## Source

### scrolling-gallery.tsx → `components/dimaac/scrolling-gallery.tsx`

```tsx
"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>
  );
}
```

### demo.tsx (the demo on the page, not installed)

```tsx
"use client";

import { ScrollingGallery, type ScrollingGalleryImage, type ScrollingGalleryProps } from "@/components/dimaac/scrolling-gallery";

// A small editorial page: an opening screen, the gallery with a huge headline that stays put
// behind the pictures, and a closing line. The pictures slide over the headline as they pass.
// Sixteen Lummi photos (Lummi License), each with its own speed.

const photos: [file: string, speed: number, alt: string][] = [
  ["fashion/orange-visor-4x5.jpg", 0.8, "Stylish woman in an orange visor and navy dress, with bold red lips and yellow earrings, against a teal background"],
  ["architecture/yellow-planes-4x5.jpg", 0.9, "Minimalist architecture with yellow and beige walls under a clear blue sky"],
  ["objects/amber-perfume-4x5.jpg", 1.1, "Elegant glass perfume bottle with amber liquid, against a green background with leaf shadows"],
  ["nature/golden-dunes-3x2.jpg", 0.8, "Vast desert landscape with golden sand dunes and distant mountains under a clear blue sky"],
  ["portraits/lime-blazer-4x5.jpg", 1.2, "A person with curly red hair wearing a lime green blazer against a bright pink background"],
  ["art/colour-cylinders-4x5.jpg", 0.6, "Colourful cylindrical objects on a vibrant geometric background in orange, red, blue and green"],
  ["dark/teal-glass-4x5.jpg", 1.0, "Moody silhouette of a person sitting on a bench against teal glass, with soft yellow light"],
  ["nature/coastline-aerial-4x5.jpg", 0.85, "Aerial view of turquoise waves crashing against a sandy beach, bordered by rugged cliffs"],
  ["art/pink-sphere-1x1.jpg", 1.15, "A glossy pink sphere reflecting a dreamy sky with clouds"],
  ["fashion/chunky-knit-4x5.jpg", 0.9, "A model in a chunky knit sweater, ruffled pants and coral lace-up boots against a warm backdrop"],
  ["architecture/pink-stucco-2x3.jpg", 1.05, "White and pink stucco walls with wooden windows under a deep blue sky"],
  ["portraits/red-coat-4x5.jpg", 0.75, "A portrait of a person in a red coat against a deep blue background"],
  ["objects/purple-vase-3x2.jpg", 1.2, "An elegant white vase with dried flowers against a deep purple background"],
  ["nature/mossy-forest-4x5.jpg", 0.8, "Lush moss-covered forest floor with misty trees in the background"],
  ["art/chrome-spheres-1x1.jpg", 1.0, "Metallic sculptures as bookends on a concrete surface, reflecting a clear blue sky"],
  ["fashion/mid-air-suit-4x5.jpg", 0.95, "A person in a black suit and futuristic accessories, mid-motion against a teal and terracotta backdrop"],
];

const images: ScrollingGalleryImage[] = photos.map(([file, speed, alt]) => ({ src: media(file), alt, speed }));

export default function Demo(props: Partial<ScrollingGalleryProps>) {
  return (
    <div className="w-full overflow-x-clip bg-[#efece6] text-[#15130f] dark:bg-[#0d0c0b] dark:text-[#ece9e2]">
      <section className="relative flex min-h-[100dvh] flex-col justify-end gap-[clamp(32px,8vh,96px)] px-5 py-5 md:px-8 md:py-7">
        <h1 className="max-w-[12ch] text-[clamp(52px,11.5vw,184px)] leading-[0.88] font-medium tracking-[-0.055em]">
          Everything moves a little differently
        </h1>

        <footer className="flex items-end justify-between gap-6">
          <p className="max-w-[32ch] text-[15px] leading-snug opacity-65">Sixteen photographs, sixteen speeds. Scroll fast and they lean into it.</p>
          <span className="font-mono text-[11px] tracking-wide uppercase opacity-70">Scroll ↓</span>
        </footer>
      </section>

      <section className="relative pt-[26vh] pb-[18vh]">
        <ScrollingGallery images={images} {...props} className={`relative z-0 ${props.className ?? ""}`} imageClassName={`shadow-[0_24px_50px_-24px_rgba(0,0,0,0.45)] ${props.imageClassName ?? ""}`} />
        {/* Two words that stay in the middle of the screen while the pictures pass. They sit in the margins on a wide screen; on a phone the pictures slide over them, and the "difference" blend keeps them readable. */}
        <div aria-hidden="true" className="pointer-events-none absolute inset-0 z-10 mix-blend-difference">
          <div className="sticky top-0 flex h-[100dvh] items-center justify-between overflow-hidden px-5 text-[clamp(52px,12.5vw,210px)] leading-none font-medium tracking-[-0.06em] text-white select-none md:px-8">
            <span>Slow</span>
            <span>Fast</span>
          </div>
        </div>
      </section>

      <section className="px-5 pt-[8vh] pb-8 md:px-8">
        <p className="max-w-[18ch] text-[clamp(32px,6vw,92px)] leading-[0.98] font-medium tracking-[-0.045em]">The page still scrolls the way you expect.</p>
      </section>
    </div>
  );
}
```

## Agent prompt

```text
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.txt
```
