Layout
A deep dive into building a Pinterest-style masonry layout — from absolute positioning algorithms and image lazy loading to virtualization, infinite scroll, and responsive column recalculation.
A masonry grid looks deceptively simple: a wall of images packed tightly with no fixed row heights. But the moment you add infinite scroll, lazy-loaded images, responsive columns, and thousands of pins, the layout becomes a performance and architecture challenge. Get the positioning wrong and you get jank; get the data flow wrong and you get blank screens.
Before writing code, we scope what this masonry must do. The goal is a layout engine that packs pins into columns of varying heights, loads images lazily as the user scrolls, and stays smooth at 60fps even with thousands of DOM-adjacent items.
I split the masonry into a small family of components. The container owns data fetching and state; the grid computes positions and manages the scroll viewport; each pin card renders an image, metadata, and actions. Separation matters because the positioning logic must not re-run when a single pin's save state flips.
The grid is the heart of the system. It receives a flat list of pins plus a column count, computes absolute positions for every pin, and renders only the visible subset when virtualization is on. The container stays above the layout details — it just feeds pins and calls loadMore when the sentinel fires.
interface MasonryGridProps {
pins: Pin[];
columnCount?: number;
minColumnWidth?: number;
gutter?: number;
loadMore?: () => void;
hasMore?: boolean;
onPinClick?: (pin: Pin) => void;
renderPin?: (pin: Pin) => React.ReactNode;
}
interface MasonryContainerProps {
initialPins: Pin[];
fetchPins: (cursor: string | null) => Promise<PinsResponse>;
minColumnWidth?: number;
gutter?: number;
}renderPin prop lets consumers customize card markup without forking the layout engine. The grid does not care what a pin looks like — it only needs width and height to position it.The diagram shows the two strategies side by side. CSS columns flows content top-to-bottom within each column, which reorders items and breaks source-order semantics. JS absolute positioning places each pin in the shortest column while keeping the original order — critical for keyboard navigation and screen readers.
The data model has two concerns: the pin entities themselves and the layout state. The pin carries its intrinsic dimensions so the engine can reserve space before the image decodes. The layout state tracks column heights and computed positions — this is what changes on resize and on every new batch of pins.
I keep positions as a Map keyed by pin id rather than embedding x/y on each pin. This lets the layout function be pure — it takes pins and dimensions, returns positions — without mutating the pin objects.
interface Pin {
id: string;
imageUrl: string;
lqipUrl: string;
width: number;
height: number;
title: string;
description: string;
author: string;
saved: boolean;
}
interface ColumnLayout {
count: number;
columnWidth: number;
heights: number[];
}
interface MasonryState {
pins: Pin[];
layout: ColumnLayout;
cursor: string | null;
loading: boolean;
hasMore: boolean;
positions: Map<string, { x: number; y: number }>;
}cursor, loading, and hasMore as siblings of the pins array.A masonry feed is paginated, so the API contract centers on cursor-based pagination. Unlike offset pagination, cursors stay stable when new pins are inserted at the top — the cursor points to "the item after this one," not "row number 40." This matters for a feed where new content arrives constantly.
The server includes image dimensions in every PinDTO. This is non-negotiable for masonry: without knowing the aspect ratio up front, the engine cannot reserve vertical space, and the layout shifts violently as each image decodes.
// GET /api/v1/pins?cursor=<opaque>&limit=20
// Response:
interface PinsResponse {
pins: PinDTO[];
nextCursor: string | null;
total: number;
}
// PinDTO from server — dimensions included so the client can
// reserve space before the image decodes, preventing layout shift.
interface PinDTO {
id: string;
image_url: string;
lqip_url: string;
width: number;
height: number;
title: string;
description: string;
author: { id: string; name: string };
}
// The cursor is opaque — the server encodes the last seen pin id
// plus sort key. The client just passes it back on the next call.
async function fetchPins(cursor: string | null): Promise<PinsResponse> {
const params = new URLSearchParams({ limit: "20" });
if (cursor) params.set("cursor", cursor);
const res = await fetch(\`/api/v1/pins?\\${params}\`);
if (!res.ok) throw new Error(\`Failed to fetch pins: \${res.status}\`);
return res.json();
}Let's walk through the three hardest pieces: the positioning algorithm, the responsive column hook, and lazy image loading. Everything else in the masonry is decorating these behaviors.
The algorithm is greedy: for each pin, find the shortest column and place the pin at its current height. We scale the pin's intrinsic height to the column width so aspect ratios are preserved. The result is a map of pin id to { x, y } that the grid applies as translate3d transforms.
function layoutMasonry(
pins: Pin[],
containerWidth: number,
columnCount: number,
gutter: number,
): Map<string, { x: number; y: number }> {
const positions = new Map<string, { x: number; y: number }>();
const colWidth = Math.floor(
(containerWidth - (columnCount - 1) * gutter) / columnCount,
);
const heights = new Array(columnCount).fill(0);
for (const pin of pins) {
// Find the shortest column
let shortest = 0;
for (let c = 1; c < columnCount; c++) {
if (heights[c] < heights[shortest]) shortest = c;
}
// Scale image height to column width to keep aspect ratio
const scaledHeight = Math.round(
(pin.height / pin.width) * colWidth,
);
const x = shortest * (colWidth + gutter);
const y = heights[shortest];
positions.set(pin.id, { x, y });
heights[shortest] += scaledHeight + gutter;
}
return positions;
}scaledHeight = (height / width) * colWidth.Column count is derived from the container width and a minimum column width. A ResizeObserver watches the container, debounces the callback, and updates the column count. When columns change, the entire layout recomputes — but only after the user stops dragging the window.
function useResponsiveColumns(
containerRef: React.RefObject<HTMLElement | null>,
minColumnWidth: number,
) {
const [columnCount, setColumnCount] = useState(3);
useEffect(() => {
if (!containerRef.current) return;
const el = containerRef.current;
let timer: ReturnType<typeof setTimeout>;
const ro = new ResizeObserver(() => {
// Debounce — rapid resizes would thrash the layout
clearTimeout(timer);
timer = setTimeout(() => {
const width = el.clientWidth;
const cols = Math.max(1, Math.floor(width / minColumnWidth));
setColumnCount(cols);
}, 150);
});
ro.observe(el);
return () => {
clearTimeout(timer);
ro.disconnect();
};
}, [containerRef, minColumnWidth]);
return columnCount;
}Loading every image up front would tank performance. Instead, each LazyImage uses an IntersectionObserver to set the src only when the image is near the viewport. A rootMargin of 300px preloads slightly ahead of scroll so images are ready before the user sees them.
function LazyImage({ src, lqip, alt, width, height }: LazyImageProps) {
const imgRef = useRef<HTMLImageElement>(null);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
const img = imgRef.current;
if (!img) return;
const io = new IntersectionObserver(
(entries, observer) => {
if (entries[0]?.isIntersecting) {
img.src = src;
observer.unobserve(img);
}
},
{ rootMargin: "300px 0px" },
);
io.observe(img);
return () => io.disconnect();
}, [src]);
return (
<div style={{ position: "relative", width, height }}>
{!loaded && (
<img
src={lqip}
alt=""
aria-hidden="true"
style={{ filter: "blur(12px)", opacity: 0.6 }}
/>
)}
<img
ref={imgRef}
alt={alt}
onLoad={() => setLoaded(true)}
style={{ opacity: loaded ? 1 : 0, transition: "opacity 0.4s" }}
/>
</div>
);
}rootMargin is your preload buffer. Too small and the user sees blank cards; too large and you waste bandwidth loading images the user may never scroll to. 300px is a good starting point — tune based on your image sizes and network.The data flow is a pipeline: the API returns pins with cursor pagination, the image cache preloads and decodes thumbnails, the masonry renderer positions each pin, and the lazy image components reveal images as they enter the viewport. A feedback loop watches the scroll sentinel and fetches the next page when the user nears the bottom.
Each pin has two image URLs: a tiny low-quality placeholder (LQIP) and the full image. The LQIP loads instantly and renders blurred behind the full image. When the full image decodes, it fades in and the LQIP fades out. This "blur-up" effect hides the loading delay and prevents layout shift.
The container coordinates fetching: it calls fetchPins with the current cursor, appends the results, updates the cursor, and triggers a re-layout. The grid receives the new pins, computes positions incrementally (only for the new batch), and renders. The sentinel observer fires loadMore when it intersects.
A masonry feed is performance-critical: the user is scrolling continuously, and any dropped frame is visible as stutter. The key strategies are DOM recycling, GPU-accelerated transforms, lazy image loading with blur-up, and passive event listeners.
With thousands of pins, mounting every card in the DOM is impossible. We compute which pins are in the viewport plus a buffer and only mount those. Off-screen pins are unmounted — their DOM nodes are recycled. The container height is set to the total content height so the scrollbar stays accurate.
function useVisibleRange(
scrollTop: number,
viewportHeight: number,
positions: Map<string, { x: number; y: number }>,
pinHeights: Map<string, number>,
buffer: number,
) {
// Only render pins whose y-position is within the viewport
// plus a buffer above and below. Everything else is recycled.
const top = scrollTop - buffer;
const bottom = scrollTop + viewportHeight + buffer;
const visible: string[] = [];
for (const [id, pos] of positions) {
const h = pinHeights.get(id) ?? 0;
if (pos.y + h >= top && pos.y <= bottom) {
visible.push(id);
}
}
return visible;
}
// In render we only mount pins in the visible set. Off-screen pins
// are unmounted, freeing DOM nodes. With 5000 pins but only ~30
// visible, the DOM stays tiny and scroll stays at 60fps.The blur-up technique uses a tiny LQIP (e.g. 20×20) as a background, with the full image fading in on top. Because the LQIP is so small, it loads in a single round-trip and fills the space immediately. The CSS uses opacity and filter transitions — both GPU-composited.
.pin-card {
break-inside: avoid;
border-radius: 14px;
overflow: hidden;
contain: layout style paint;
will-change: transform;
}
.pin-image-wrap {
position: relative;
background: var(--pin-skeleton, #141414);
}
.pin-lqip {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0.5;
filter: blur(12px);
transition: opacity 0.4s ease-out;
}
.pin-image {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0;
filter: blur(20px);
transition: opacity 0.4s ease-out, filter 0.4s ease-out;
}
.pin-image.loaded {
opacity: 1;
filter: blur(0);
}
.pin-image.loaded ~ .pin-lqip {
opacity: 0;
}
@media (prefers-reduced-motion: reduce) {
.pin-image,
.pin-lqip {
transition: none;
}
}Every pin is positioned with translate3d rather than top/left. Transforms are composited on the GPU and never trigger layout. We add will-change: transform to pin cards andcontain: layout style paint to isolate each card's rendering. Scroll listeners are registered with passive: true so the browser can scroll without waiting for our handler.
A masonry feed renders user-generated content — images and text from arbitrary authors. We must restrict where images can load from, sanitize any HTML in pin descriptions, and rate-limit the infinite scroll trigger to prevent API abuse.
The img-src directive in the Content Security Policy restricts image loading to known CDN and placeholder domains. This prevents data exfiltration via crafted image URLs — an attacker cannot make the browser send a request to an arbitrary endpoint disguised as an image.
Pin descriptions may contain user-authored HTML. Never pass them raw into dangerouslySetInnerHTML. Always sanitize with DOMPurify and restrict to a safe tag allowlist. An XSS inside a masonry card can phish for credentials or hijack the save action.
The infinite scroll observer can fire rapidly during fast scrolling or programmatic scroll-to-bottom. Wrap the fetch in a guard that enforces a minimum interval between requests. This protects the API from accidental abuse and prevents duplicate fetches when the sentinel flutters in and out of view.
// Content Security Policy for images — restrict to known CDN
// and placeholder domains. Prevents exfiltration via image URLs.
const IMAGE_CSP =
"img-src 'self' https://cdn.frontendx.dev https://picsum.photos data:;";
// Pin descriptions are user-generated HTML. Always sanitize before
// rendering — never use dangerouslySetInnerHTML with raw input.
import DOMPurify from "dompurify";
function PinDescription({ html }: { html: string }) {
const clean = useMemo(
() =>
DOMPurify.sanitize(html, {
ALLOWED_TAGS: ["b", "i", "em", "strong", "a", "br"],
}),
[html],
);
return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}
// Rate-limit the infinite scroll trigger to prevent API abuse.
// A rogue script or rapid resize could fire hundreds of fetches.
const MIN_FETCH_INTERVAL = 500;
let lastFetch = 0;
function guardedLoadMore(loadMore: () => void) {
const now = Date.now();
if (now - lastFetch < MIN_FETCH_INTERVAL) return;
lastFetch = now;
loadMore();
}A masonry layout has pure logic (positioning math) and impure behavior (scroll, resize, image loading). We test them separately: unit tests for the algorithm, integration tests for the scroll pipeline, and e2e tests for the full infinite scroll experience.
The layoutMasonry function is pure, so it is trivial to unit test. We verify that the first pin lands at the origin, that subsequent pins go to the shortest column, and that heights scale correctly. These tests catch off-by-one errors in the gutter math and aspect-ratio scaling.
describe("layoutMasonry", () => {
const makePin = (id: string, w: number, h: number): Pin => ({
id, width: w, height: h, imageUrl: "", lqipUrl: "",
title: "", description: "", author: "", saved: false,
});
const pins = [
makePin("1", 400, 600),
makePin("2", 400, 300),
makePin("3", 400, 500),
];
it("places the first pin in column 0 at y=0", () => {
const pos = layoutMasonry(pins, 900, 3, 12);
expect(pos.get("1")).toEqual({ x: 0, y: 0 });
});
it("assigns each subsequent pin to the shortest column", () => {
const pos = layoutMasonry(pins, 900, 3, 12);
// colWidth = (900 - 24) / 3 = 292
expect(pos.get("2")?.x).toBe(292);
expect(pos.get("3")?.x).toBe(584);
});
it("scales pin height to match the column width", () => {
const pos = layoutMasonry([makePin("1", 400, 600)], 900, 3, 12);
// scaledHeight = (600 / 400) * 292 = 438
expect(pos.get("1")?.x).toBe(0);
});
it("returns an empty map for zero pins", () => {
const pos = layoutMasonry([], 900, 3, 12);
expect(pos.size).toBe(0);
});
});We mount the grid with a mock fetch and simulate scroll events. Tests verify that loadMore fires when the sentinel intersects, that the cursor advances, and that a resize triggers a relayout with the new column count. The IntersectionObserver is mocked to fire on demand.
Playwright drives a real browser against the live page. We scroll the sentinel into view and assert that the pin count increased by the batch size. We also verify that images lazy-load — the data-src attribute is set before scroll and the loaded class appears after.
test("loads more pins when scrolling near the bottom", async ({ page }) => {
await page.goto("/system-design/pinterest-masonry");
// Wait for the initial batch of pins
await expect(page.locator(".pin-card")).toHaveCount(20);
const initialCount = await page.locator(".pin-card").count();
// Scroll the sentinel into view to trigger infinite scroll
await page.locator(".sentinel").scrollIntoViewIfNeeded();
await page.waitForTimeout(500);
// Verify a new batch was appended
await expect(page.locator(".pin-card")).toHaveCount(initialCount + 10);
});
test("images lazy-load when scrolled into view", async ({ page }) => {
await page.goto("/system-design/pinterest-masonry");
const firstImg = page.locator(".pin-image").first();
// data-src is set but src is empty until visible
await expect(firstImg).toHaveAttribute("data-src", /.+/);
await firstImg.scrollIntoViewIfNeeded();
await expect(firstImg).toHaveClass(/loaded/);
});A masonry grid is visually complex, but that does not excuse it from accessibility. Keyboard users must be able to navigate pins, screen readers must announce each pin's content, and reduced-motion users must not be subjected to blur transitions.
article with tabIndex=0.Tab moves between pins in source order; Enter or Space opens the detail view. The save button is a real button with aria-pressed.alt text from the pin description or title. The LQIP is decorative and marked aria-hidden so screen readers skip it.prefers-reduced-motion: reduce is active. Images appear instantly without the fade and blur animation.section with an aria-label. The loading sentinel announces aria-live="polite" so screen-reader users know when new content loads.// Each pin card is a focusable article with an accessible name
<article
tabIndex={0}
aria-label={\`\${pin.title} by \${pin.author}\`}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onPinClick?.(pin);
}
}}
>
<LazyImage
src={pin.imageUrl}
lqip={pin.lqipUrl}
alt={pin.description || pin.title}
width={pin.width}
height={pin.height}
/>
<button aria-pressed={pin.saved} aria-label="Save pin">
Save
</button>
</article>Here's the Pinterest masonry running live. Scroll through the grid, hover a pin to see the save button, and watch how images lazy-load with a blur-up effect as they enter the viewport. Keep scrolling to trigger infinite scroll — new pins load in batches of ten.
Scroll near the bottom to load more pins. Hover any pin to reveal the save button.
If you remember only a few things from this article, make them these:
Absolute positioning preserves source order for keyboard and screen-reader users.
Greedy packing minimizes vertical gaps and balances column heights.
Tiny placeholder fills space instantly; full image fades in on decode.
Unmount off-screen pins to keep the DOM light and scroll at 60fps.
Recalculate column count on resize, then reposition every pin.
Stable cursors survive new inserts; translate3d avoids layout thrash.