# GSAP image gallery: filterable grid with Flip layout transitions

> Build a filterable GSAP image gallery with Flip layout transitions, staggered entry and exit animations, and reduced-motion support. Complete code included.

Published 2026-11-19 by Jake. Canonical: https://gsapvault.com/blog/gsap-image-gallery

---
Filtering an image gallery in plain CSS is abrupt: hide half the grid with `display: none` and the remaining photos snap into their new columns in a single frame. GSAP's `Flip` plugin turns that layout jump into a smooth glide by measuring where every card starts, letting CSS put them in their new positions, and animating the difference. Here is a basic version with category filters, staggered enter and leave animations, and a reduced-motion fallback.

## What you'll build

A responsive CSS Grid gallery with category filter buttons. Clicking a category hides non-matching cards, fades them out in place, slides the surviving cards into their new grid slots, and fades newly revealed cards back in. Under `prefers-reduced-motion`, the filter still works and updates the grid immediately with no motion.

[Live interactive demo](https://gsapvault.com/demos/filter-reflow-gallery/index.html)

## Step 1: Add GSAP and Flip

Add GSAP core and the `Flip` plugin before your closing `</body>` tag:

```html
```

## Step 2: Add the markup

Give the filter buttons a `data-filter` attribute and each gallery card a matching `data-category`. Using native `<button>` elements with `aria-pressed` keeps keyboard navigation and screen reader state intact without extra code.

```html
<section class="gallery-section" aria-label="Project gallery">
  <div class="gallery-filters" role="group" aria-label="Filter gallery by category">
    <button type="button" class="filter-btn is-active" data-filter="all" aria-pressed="true">All</button>
    <button type="button" class="filter-btn" data-filter="architecture" aria-pressed="false">Architecture</button>
    <button type="button" class="filter-btn" data-filter="coastal" aria-pressed="false">Coastal</button>
    <button type="button" class="filter-btn" data-filter="studio" aria-pressed="false">Studio</button>
  </div>

  <div class="gallery-grid">
    <figure class="gallery-card" data-category="architecture">
      <img src="photo-1.jpg" alt="Concrete stairwell in morning light" width="800" height="600" loading="lazy">
      <figcaption>North Stairwell</figcaption>
    </figure>
    <figure class="gallery-card" data-category="coastal">
      <img src="photo-2.jpg" alt="Low tide across basalt rocks" width="800" height="600" loading="lazy">
      <figcaption>Basalt Shore</figcaption>
    </figure>
    <figure class="gallery-card" data-category="studio">
      <img src="photo-3.jpg" alt="Ceramic vessels arranged on a timber bench" width="800" height="600" loading="lazy">
      <figcaption>Kiln Study</figcaption>
    </figure>
    <figure class="gallery-card" data-category="architecture">
      <img src="photo-4.jpg" alt="Glass facade reflecting clouds" width="800" height="600" loading="lazy">
      <figcaption>East Atrium</figcaption>
    </figure>
    <figure class="gallery-card" data-category="coastal">
      <img src="photo-5.jpg" alt="Harbour wall at dusk" width="800" height="600" loading="lazy">
      <figcaption>Breakwater</figcaption>
    </figure>
    <figure class="gallery-card" data-category="studio">
      <img src="photo-6.jpg" alt="Linen fabric folded beside a window" width="800" height="600" loading="lazy">
      <figcaption>Loom Room</figcaption>
    </figure>
  </div>
</section>
```

## Step 3: Add the CSS

The grid uses standard CSS Grid. The only rule Flip specifically relies on is `position: relative` on `.gallery-grid` so `absolute: true` positions cards relative to the grid container rather than the page.

```css
.gallery-section {
  max-width: 72rem;
  margin: 0 auto;
  padding: 2rem 1.25rem;
}

.gallery-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
}

.filter-btn {
  padding: 0.5rem 1rem;
  border: 1px solid #d4d4d8;
  border-radius: 999px;
  background: transparent;
  color: inherit;
  font: inherit;
  cursor: pointer;
}

.filter-btn.is-active {
  background: #18181b;
  border-color: #18181b;
  color: #fafafa;
}

.gallery-grid {
  position: relative;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 1.25rem;
}

.gallery-card {
  margin: 0;
  overflow: hidden;
  border-radius: 10px;
  background: #f4f4f5;
}

.gallery-card img {
  display: block;
  width: 100%;
  aspect-ratio: 4 / 3;
  object-fit: cover;
}

.gallery-card figcaption {
  padding: 0.75rem 1rem;
  font-size: 0.9rem;
}

.gallery-card.is-hidden {
  display: none;
}
```

Setting `aspect-ratio: 4 / 3` on the images matters more than it looks: without a fixed ratio, a lazy-loaded image changes card height when it arrives, and Flip measures the wrong box.

## Step 4: Add the Flip script

Add this JavaScript after the GSAP and Flip script tags:

```javascript
document.addEventListener('DOMContentLoaded', () => {
  gsap.registerPlugin(Flip);

  const buttons = gsap.utils.toArray('.filter-btn');
  const cards = gsap.utils.toArray('.gallery-card');
  const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
  let activeFilter = 'all';

  function applyFilter(filter) {
    if (filter === activeFilter) return;
    activeFilter = filter;

    buttons.forEach((btn) => {
      const isMatch = btn.dataset.filter === filter;
      btn.classList.toggle('is-active', isMatch);
      btn.setAttribute('aria-pressed', String(isMatch));
    });

    // Under reduced motion, swap visibility immediately and skip Flip.
    if (reduceMotion.matches) {
      cards.forEach((card) => {
        const show = filter === 'all' || card.dataset.category === filter;
        card.classList.toggle('is-hidden', !show);
      });
      return;
    }

    // 1. Record every card's current position and visibility.
    const state = Flip.getState(cards);

    // 2. Apply the real DOM/CSS change.
    cards.forEach((card) => {
      const show = filter === 'all' || card.dataset.category === filter;
      card.classList.toggle('is-hidden', !show);
    });

    // 3. Animate from the recorded state to the new layout.
    Flip.from(state, {
      duration: 0.55,
      ease: 'power2.inOut',
      absolute: true,
      stagger: 0.03,
      onEnter: (elements) =>
        gsap.fromTo(
          elements,
          { opacity: 0, scale: 0.9 },
          { opacity: 1, scale: 1, duration: 0.4, ease: 'power2.out' }
        ),
      onLeave: (elements) =>
        gsap.to(elements, {
          opacity: 0,
          scale: 0.9,
          duration: 0.3,
          ease: 'power2.in',
        }),
    });
  }

  buttons.forEach((btn) => {
    btn.addEventListener('click', () => applyFilter(btn.dataset.filter));
  });
});
```

Three lines do the real work here:

- **`Flip.getState(cards)`** runs before any class changes, capturing the bounding rectangle and `display` state of every card, including ones currently hidden.
- **`absolute: true`** temporarily positions animated cards absolutely during the transition. Without it, a card fading out in `onLeave` stays in the grid flow until its tween finishes, causing remaining cards to sit in the wrong cells and then snap.
- **`onEnter` and `onLeave`** only fire for cards that switched between `display: none` and visible. Cards that stay visible simply glide to their new grid coordinates with no opacity flicker.

Notice also where the reduced-motion check sits: inside `applyFilter()` rather than at page load. The filter buttons still work for visitors who prefer reduced motion, and if someone toggles the OS setting mid-session, the next click respects it.

## That's it

Click any category button and the non-matching cards scale down and fade out while the remaining photos glide into their new positions. Click All and the hidden cards fade back in as the grid opens up around them. Under reduced motion, the filter updates the grid cleanly in one step.

## Making it yours

- **Pace and feel.** `duration: 0.55` with `power2.inOut` is crisp and readable. Pushing duration past `0.8` makes frequent filter clicks feel sluggish; `power3.out` makes the cards launch faster and settle gently.
- **Stagger.** `stagger: 0.03` breaks up the wall-of-cards movement so the grid reads as individual photos moving rather than a rigid block. Set it to `0` if you have more than 24 items, or the last card starts noticeably late.
- **Container height.** When filtering down to two cards, the page below the gallery will pull upward immediately because the hidden cards leave document flow. If you have a footer right underneath, set a `min-height` on `.gallery-grid` or animate the container height separately.
- **Multiple tags per card.** Store space-separated categories like `data-category="coastal studio"` and replace the equality check with `card.dataset.category.split(' ').includes(filter)`.

## A note on performance

Flip animates `transform` (`translate` and `scale`), which stays on the compositor and avoids layout thrashing during the tween. The one expensive moment is `Flip.getState()`, which forces a single synchronous layout read right when the user clicks. That is fine for a few dozen cards.

Two things will make a Flip gallery stutter even at small counts: animating `box-shadow` or `filter` inside `onEnter`/`onLeave`, and letting full-resolution unresized photos decode on the main thread when they first become visible. Serve appropriately sized thumbnails, set `width` and `height` attributes on every `<img>`, and keep `onEnter` and `onLeave` limited to `opacity` and `scale`.

---

## Want more control?

This basic version gives you a clean, filterable CSS Grid gallery. The [Filter Reflow Gallery](/effects/filter-reflow-gallery) takes the pattern further with features this tutorial leaves out:

- **Masonry layout** across mixed portrait, square and landscape aspect ratios
- **Directional wave reflow** that ripples outward from whichever filter chip was clicked
- **In-place photo expansion** that opens any selected image across two columns with its caption, without leaving the grid
- **Keyboard navigation and focus management** across chips, cards and expanded views
- **Rapid-click handling** that cleanly interrupts mid-flight transitions without leaving orphaned opacity or inline styles

If you want a different kind of GSAP gallery altogether, the library also includes the [Counter-Scroll Column Gallery](/effects/counter-scroll-gallery) for scroll-driven opposing columns, the [Fullscreen Flip Gallery](/effects/fullscreen-flip-gallery) for full-bleed hinged page turns, and the [Fisheye Grid Gallery](/effects/fisheye-grid-gallery) for pointer-driven dock magnification.

[View the full effect with all options →](/effects/filter-reflow-gallery)

*More of this kind in the [GSAP image galleries](/categories/gsap-image-galleries) collection.*