How to Lay Out Cards of Different Heights Without Gaps in React
To lay out cards of different heights in columns without gaps, place each card in order under the shortest column. React only needs to track the width of the container and the height of each card. Both are measured with ResizeObserver, the card positions are calculated from those values, and the cards are placed with position: absolute. This suits a list of cards whose heights vary with image or text length, shown in the masonry style.
Here I built a Masonry component that does this and compared it with a layout made with CSS multi-column (column-width). I also checked what happens when cards are added and when images load later and change card heights.
The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153 (headless). I used React 19.3.1, TypeScript 7.0.2, and Playwright 1.63.0, and read the card positions from Playwright. The card images are not photos but single-color PNGs drawn with pngjs. I did not test Firefox, Safari, smartphone browsers, the speed with hundreds of cards, server-side rendering (SSR), or behavior under the development Strict Mode.

- 1. CSS multi-column also lays out cards, but the order runs down each column
- 2. A Masonry component that places each card under the shortest column
- 3. Layout results and what happens when a card is added
- 4. When images load later, card heights change
- 5. A standard CSS layout for this arrangement is still under discussion
CSS multi-column also lays out cards, but the order runs down each column
If you want to use only CSS, you can use multi-column layout. Set the target column width with column-width, and add break-inside: avoid so that a card is not split across two columns.
.columns { column-width: 220px; column-gap: 16px; }
.columns-item { break-inside: avoid; margin-bottom: 16px; }
I placed 12 cards on an 800px-wide screen. They formed 3 columns, and the gap between cards was 16px everywhere. However, the cards fill the left column from top to bottom first.
--- Multi-column (column-width: 220px), width 800px ---
列の数: 3(カードの幅 242.7px)
1列目(左から 0px): カード 1, 2, 3, 4 / カードの間 16.0px / 下端 1319.3px
2列目(左から 259px): カード 5, 6, 7, 8 / カードの間 16.0px / 下端 1137.3px
3列目(左から 517px): カード 9, 10, 11, 12 / カードの間 16.0px / 下端 1246.5px
重なっているカードの組: 0 / 列の下端の差: 182.0px
For a list sorted newest first, cards 1 to 4, the newest, are stacked down the left column, and card 9, an older one, appears at the top right. A reader who scans from left to right will find the order hard to follow.
Also, multi-column layout splits the content evenly across the columns (this is the behavior of the initial value balance of column-fill). When I added one card, the division was recalculated. After adding card 13, the positions of cards 9 to 12, which were already placed, changed.
段組み: カード 13 を追加 → 左から 517px の列、上から 909.1px / 位置が変わったカード: 4枚(9, 10, 11, 12)
In a list that grows downward through a "Load more" button, a card you are reading would move to another column.

A Masonry component that places each card under the shortest column
To keep the left-to-right reading order, go through the cards in order and place each one under the currently shortest column. If two or more columns are tied, choose the leftmost. Here is this logic in React as the Masonry component. The content is passed in through renderItem, so it is separate from the card's appearance.
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
type Props<T> = {
items: T[];
getKey: (item: T) => string;
renderItem: (item: T) => ReactNode;
// Target column width. The number of columns is chosen so that no column is narrower than this
columnWidth?: number;
gap?: number;
};
export function Masonry<T>({ items, getKey, renderItem, columnWidth = 220, gap = 16 }: Props<T>) {
const containerRef = useRef<HTMLDivElement>(null);
const observerRef = useRef<ResizeObserver | null>(null);
const [width, setWidth] = useState(0);
const [heights, setHeights] = useState(() => new Map<string, number>());
// Measure the width of the container, and measure it again whenever the screen width changes
useLayoutEffect(() => {
const el = containerRef.current!;
setWidth(el.clientWidth);
const ro = new ResizeObserver(() => setWidth(el.clientWidth));
ro.observe(el);
return () => ro.disconnect();
}, []);
// Measure the height of each card. Measure again whenever the height changes, for example when an image finishes loading
const measureRef = useCallback((el: HTMLDivElement | null) => {
if (!el) return;
observerRef.current ??= new ResizeObserver((entries) => {
setHeights((prev) => {
let next = prev;
for (const entry of entries) {
const key = (entry.target as HTMLElement).dataset.key!;
const height = entry.borderBoxSize[0].blockSize;
if (prev.get(key) === height) continue;
if (next === prev) next = new Map(prev);
next.set(key, height);
}
// If no height has changed, return the same Map to stop re-rendering
return next;
});
});
const ro = observerRef.current;
ro.observe(el);
return () => ro.unobserve(el);
}, []);
// The number of columns and the width of one column
const columns = Math.max(1, Math.floor((width + gap) / (columnWidth + gap)));
const colWidth = (width - gap * (columns - 1)) / columns;
// Go through the cards in order and place each one under the shortest column
const colHeights: number[] = new Array(columns).fill(0);
const positions = items.map((item) => {
const height = heights.get(getKey(item));
// Do not place a card whose height has not been measured yet (keep it hidden)
if (height === undefined) return null;
const col = colHeights.indexOf(Math.min(...colHeights));
const pos = { x: col * (colWidth + gap), y: colHeights[col] };
colHeights[col] += height + gap;
return pos;
});
const totalHeight = Math.max(0, Math.max(...colHeights) - gap);
return (
<div ref={containerRef} className="masonry" style={{ position: 'relative', height: totalHeight }}>
{width > 0 &&
items.map((item, i) => {
const key = getKey(item);
const pos = positions[i];
return (
<div
key={key}
ref={measureRef}
data-key={key}
className="masonry-item"
style={{
position: 'absolute',
top: 0,
left: 0,
width: colWidth,
transform: pos ? `translate(${pos.x}px, ${pos.y}px)` : undefined,
visibility: pos ? 'visible' : 'hidden',
}}
>
{renderItem(item)}
</div>
);
})}
</div>
);
}
The number of columns is the largest value for which no column is narrower than the target columnWidth (220px). The leftover width is spread across the columns. On an 800px screen the container is 760px wide, so there are 3 columns of 242.7px each.
The container width is read once inside useLayoutEffect, and after that it is re-read each time ResizeObserver reports a change. A state update made inside useLayoutEffect is applied before the browser paints the screen, so the width is never painted as 0.
Each card's height is measured with a ResizeObserver on the div that wraps the card. The blockSize of borderBoxSize is the height including the border for horizontal writing. A card can only be measured after it is in the DOM, so a card that has not been measured yet is kept hidden with visibility: hidden. Once it is measured, its position is calculated and it is shown.
Observation is started and stopped in a ref callback. In React 19, the function returned from the ref callback is called when the element is removed. If a new function were created on every render, observation would be stopped and started again on every render, so useCallback keeps the same function. Also, setHeights returns the previous Map when no height has changed. If you pass the same value to a state setter, React skips re-rendering the component and its children. So when a measurement does not change any height, the extra re-render is avoided.
The caller passes the array of cards, a function that returns the key, and a function that draws each card.
import { useState } from 'react';
import { Masonry } from './Masonry';
import { CardView } from './CardView';
import { makeCard } from './cards';
export function App({ imageSize = true }: { imageSize?: boolean }) {
const [cards, setCards] = useState(() => Array.from({ length: 12 }, (_, i) => makeCard(i + 1)));
return (
<main>
<div className="toolbar">
<button onClick={() => setCards((prev) => [...prev, makeCard(prev.length + 1)])}>カードを追加</button>
<span className="count">{cards.length}枚</span>
</div>
<Masonry
items={cards}
getKey={(card) => String(card.id)}
renderItem={(card) => <CardView card={card} imageSize={imageSize} />}
/>
</main>
);
}
Each card consists of an image, a heading, and text. The image has width and height attributes (imageSize is a prop I added so that the case without them can be compared).
import type { Card } from './cards';
// Give the image width and height attributes. The space for the aspect ratio is reserved before the image loads
export function CardView({ card, imageSize = true }: { card: Card; imageSize?: boolean }) {
return (
<article className="card">
<img
src={`img/${card.imageHeight}.png`}
alt=""
{...(imageSize ? { width: 400, height: card.imageHeight } : {})}
/>
<h2>カード {card.id}</h2>
<p>{card.text}</p>
</article>
);
}
.card { background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgb(0 0 0 / 0.15); }
.card img { display: block; width: 100%; height: auto; }
Layout results and what happens when a card is added
These are the results for 12 cards on an 800px-wide screen. Cards 1, 2, and 3 fill the top row from the left, and the rest go into the shorter columns. Every column has a 16px gap between cards, and no cards overlap. The height of the container is 1327.7px, the same as the bottom edge of column 2, the longest column.
--- Masonry (placed in the shortest column), width 800px ---
列の数: 3(カードの幅 242.7px)
1列目(左から 0px): カード 1, 5, 7, 10 / カードの間 16.0px / 下端 1196.1px
2列目(左から 259px): カード 2, 6, 9, 12 / カードの間 16.0px / 下端 1327.7px
3列目(左から 517px): カード 3, 4, 8, 11 / カードの間 16.0px / 下端 1179.4px
重なっているカードの組: 0 / 列の下端の差: 148.3px
並べる場所の高さ: 1327.7px
When I added one card, it went under column 3, which was the shortest (bottom edge 1179.4px), at 1179.4 + 16 = 1195.4px. No other card moved.
Masonry: カード 13 を追加 → 左から 517px の列、上から 1195.4px / 位置が変わったカード: 0枚
Cards before the added one are calculated again with the same order and heights, so their positions do not change. This layout works well for a list that grows downward.
When I changed the screen width, ResizeObserver reported the change in the container width, and the number of columns changed. At 520px there were 2 columns, and at 360px there was 1. When the column width changes, text wraps differently and card heights change, but these are also re-measured by the per-card ResizeObserver.
幅 520px:
列の数: 2(カードの幅 236.0px)
1列目(左から 0px): カード 1, 3, 5, 7, 9, 11, 13 / カードの間 16.0px / 下端 2042.0px
2列目(左から 252px): カード 2, 4, 6, 8, 10, 12 / カードの間 16.0px / 下端 1880.4px
重なっているカードの組: 0 / 列の下端の差: 161.6px
幅 360px:
列の数: 1(カードの幅 328.0px)
1列目(左から 0px): カード 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 / カードの間 16.0px / 下端 4705.6px
重なっているカードの組: 0 / 列の下端の差: 0.0px
When I set the width back to 800px, the layout returned to the same 3-column arrangement as after adding card 13.
When images load later, card heights change
Card images can arrive later than the page. I delayed only the images by 600ms on a test server and compared the layout before and after they arrived.
When the images had width and height attributes, the height of card 1 was 313.2px before the image arrived and did not change after it arrived. As described in the MDN description of the img element, the browser computes the aspect ratio from the two values and reserves the space before the image loads. This aspect ratio was used even though the CSS was width: 100%; height: auto;.
--- With width and height attributes on the image (image arrives 600ms late) ---
読み込む前: 届いていた画像 0枚 / カード 1 の高さ 313.2px
読み込んだあと: カード 1 の高さ 313.2px / 読み込みの前後で高さが変わったカード: 0枚 / 位置が変わったカード: 0枚
Without the attributes, the height of card 1 before the image arrived was 94.8px, and it became 313.2px once the image arrived. The heights of all 12 cards changed, and the positions of 9 of them changed. The cards were laid out again with the re-measured heights, so they did not overlap, but the order was rearranged while the images were loading.
--- Without width and height attributes on the image (image arrives 600ms late) ---
読み込む前: 届いていた画像 0枚 / カード 1 の高さ 94.8px
列の数: 3(カードの幅 242.7px)
1列目(左から 0px): カード 1, 4, 7, 9, 12 / カードの間 16.0px / 下端 515.5px
2列目(左から 259px): カード 2, 6, 11 / カードの間 16.0px / 下端 473.1px
3列目(左から 517px): カード 3, 5, 8, 10 / カードの間 16.0px / 下端 494.3px
重なっているカードの組: 0 / 列の下端の差: 42.4px
読み込んだあと: カード 1 の高さ 313.2px / 高さが変わったカード: 12枚 / 位置が変わったカード: 9枚
A card's height can change after it has been placed, so do not measure the height only once at the start. Re-measure it with ResizeObserver whenever it changes. If you give images width and height attributes, the order will not be rearranged while they load.
I also checked what happens if the height is measured only once. I replaced ResizeObserver with a version that passes only the first notification for each element to the callback. Images again had no width and height and were delayed by 600ms. The output below shows only the result after the images arrived (the result before arrival is the same as the case without width and height).
--- Same conditions, with the card height measured only once ---
列の数: 3(カードの幅 242.7px)
1列目(左から 0px): カード 1, 4, 7, 9, 12 / カードの間 -202.4, -153.9, -105.3, -226.7px / 下端 661.1px
2列目(左から 259px): カード 2, 6, 11 / カードの間 -226.7, -141.7px / 下端 642.9px
3列目(左から 517px): カード 3, 5, 8, 10 / カードの間 -178.1, -129.6, -202.4px / 下端 688.4px
重なっているカードの組: 14 / 列の下端の差: 45.5px
Because the positions were fixed at the heights from before the images arrived, the gaps between cards became negative, and 14 pairs of cards overlapped.
A standard CSS layout for this arrangement is still under discussion
CSS has a proposal for the same kind of layout, where each card goes into the currently shortest column. It is display: grid-lanes in the CSS Grid Layout Module Level 3 draft. However, in Chromium 153, which I used for the tests, CSS.supports('display', 'grid-lanes') returned false.
CSS.supports('display', 'grid-lanes'): false
In browsers that do not support it yet, such as Chromium 153, you need to calculate the positions in JavaScript as shown here.





