Masonry
Cards of different heights: measured layout, images and adaptive columns.
When to use
Masonry places cards or images of varying heights in the shortest columns. Use it for collections and galleries with uneven content. For regular lines with a common height, Grid is suitable.
Layout depends on DOM measurements. In the current API, elements appear after mount; with SSR, an empty root remains. If the content must be read without JavaScript, choose a different page composition.
Card data and markings
items contains key, data and optional children, column and height. The key must remain unique after conversion to a string and persist when the array is updated.
| Problem | Setting | Example |
|---|---|---|
| Place cards of different heights | items, itemRender |
Cards of different heights |
| Change the number of columns on the screen | responsive columns |
Adaptive speakers |
| Change topic thresholds and intervals | theme.token.screen* |
Thresholds, columns and intervals |
| Lay out images | Content Dimensions | Images with different aspect ratios |
| Update card contents | fresh |
Adding and editing cards |
| Prefer a specific column | item.column |
Preferred Column |
itemRender - Svelte snippet with item fields, index and calculated column. item.children takes precedence if not null/undefined: even 0, false and the empty string override the renderer. The general children of Masonry itself does not create cards.
The item.height field does not specify the layout geometry: the measured DOM height is used. Assign height to content or let text and image determine it, as in the examples.
Columns, spacing and measurement
columns accepts a positive integer or a responsive map by viewport. By default there are three columns; for a map without a match, xs is used, then one column. Fractional values are not rounded and are not suitable for this setting.
gutter sets the spacing, a couple - horizontal and vertical separately. For the current implementation, use numbers in px or responsive map of numbers. The GridGutter type allows a CSS string, but Masonry adds px and uses the value in arithmetic without string normalization; this scenario is still limited.
In a theme with the Source engine enabled, responsive columns and both gutter axes use the global theme.token.screen*. In normal mode without a theme, standard borders apply. Xs reads screenXSMax, sm and further - screenSM/screenMD/…; min/max values additionally check the order. The wrong order is rejected already at SSR, although the cards have not yet been created.
Example of thresholds changes 576/768 to 640/900, shows inheritance and theme.inherit:false. Design tokens are updated without remount: root, editor, selection and FormData are preserved. If screenSM is greater than screenSMMin, there may be a gap between xs and sm without a match. columns uses xs or one column, and each gutter is resolved separately and can become null; fallback of columns is not carried over to intervals.
By default, the component monitors the root and load/error events of images; changing items also triggers recalculation. fresh includes additional monitoring of card sizes when the content changes arbitrarily. Dynamic example changes height without changing card identity.
onLayoutChange returns the elements in their original order with the calculated column and their original fields. This is a notice of allocation, not a new order of data. The preferred item.column is limited to existing columns.
Design and life cycle
classNames/styles set root/item object or function from props; callback sees the allowed number of columns. styles contains CSS strings. The card geometry is applied after semantic item styles, so set the position and dimensions via the layout API and its contents.
ConfigProvider.masonry inherits the design; the passed nested record replaces the parent one. Semantic example shows the provider's local styles and defaults. There are no proprietary named component tokens; the colors and font set the cards' content and overall theme.
bind:nativeElement returns the root div. When unmounted, the component clears the ref, observers, and subscriptions. Native requests, Object URLs, and content resources are released by the application.
Visual distribution by columns preserves the original order of elements in the DOM. For cards with interactive activities, check the reading and Tab sequence along with changing the number of columns.
A non-empty local prefixCls changes the root/item/motion classes. The empty string and undefined inherit ConfigProvider.prefixCls with the -masonry suffix, defaulting to ant-masonry. Semantic callbacks receive the original local prefixCls value rather than the full resolved class. Example of prefixes shows the same class in areas with different numbers of columns, fresh and saving the editor when updating.
The cell width service variable follows the general prefix without dots: --suite-masonry-item-width. It is independent of the local class and theme.cssVar.prefix; set columns and intervals using columns/gutter. Svelte preserves the direction from ConfigProvider.direction and isolates root/RTL rules. The RTL side effect of the name ant-masonry-rtl from the general reference stylesheet is not reproduced.
Examples
Cards of different heights
Elements are distributed into the shortest columns after measuring the DOM. onLayoutChange shows the calculated distribution.
<script lang="ts">
import { Masonry } from '@woodger/antd';
const items = [90, 130, 70, 110, 150, 80].map((height, key) => ({ key, data: { height } }));
let distribution = $state(("After measurement"));
</script>
<style>
.tile {
display: grid;
align-content: center;
gap: 8px;
box-sizing: border-box;
padding: 12px;
border-radius: 8px;
background: var(--ant-color-primary-bg);
text-align: center;
overflow-wrap: anywhere;
}
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<Masonry
items={(items)}
columns={(3)}
gutter={12}
onLayoutChange={next => {
distribution = next.map(item => `${Number(
item.key
) + 1}→${item.column + 1}`).join(', ');
}}
>
{#snippet itemRender(item)}
<div class="tile" style={`height:${item.data.height}px`}>
{(item.index + 1)}
</div>
{/snippet}
</Masonry>
<output aria-label={("Masonry Distribution")}>{distribution}</output>
Adaptive speakers
The number of columns and both intervals change according to the viewport. Grid thresholds from xs to xxxl are supported.
<script lang="ts">
import { Masonry } from '@woodger/antd';
const items = [90, 130, 70, 110, 150, 80].map((height, key) => ({ key, data: { height } }));
</script>
<style>
.tile {
display: grid;
align-content: center;
gap: 8px;
box-sizing: border-box;
padding: 12px;
border-radius: 8px;
background: var(--ant-color-primary-bg);
text-align: center;
overflow-wrap: anywhere;
}
</style>
<Masonry items={(items)} columns={({ xs: 1, sm: 2, lg: 3 })} gutter={[{
xs: 8,
sm: 16,
lg: 24
}, 12]}>
{#snippet itemRender(item)}
<div class="tile" style={`height:${item.data.height}px`}>{("Card ")}{(item.index + 1)}</div>
{/snippet}
</Masonry>
Images with different aspect ratios
Masonry monitors image loading and re-measures height. This uses locally generated SVGs without external requests.
<script lang="ts">
import { Masonry } from '@woodger/antd';
const items = [160, 240, 190, 280, 180, 210].map((height, key) => ({
key,
data: {
src: `data:image/svg+xml,${encodeURIComponent(
`<svg xmlns="http://www.w3.org/2000/svg" width="240" height="${height}" viewBox="0 0 240 ${height}"><rect width="240" height="${height}" fill="${key
% 2
? '#08979c'
: '#722ed1'}"/><circle cx="120" cy="${height
/ 2}" r="48" fill="white" opacity=".3"/></svg>`
)}`
}
}));
</script>
<style>
img {
display: block;
width: 100%;
border-radius: 8px;
}
</style>
<Masonry items={(items)} columns={(2)} gutter={12}>
{#snippet itemRender(item)}<img src={item.data.src} alt={("Geometric illustration " + String((item.index + 1)) + "")} />{/snippet}
</Masonry>
Adding and changing cards
fresh observes the height of items. A stable key preserves content as it is added, removed, and changed in height.
<script lang="ts">
import { Button, Masonry } from '@woodger/antd';
let items = $state([90, 130, 70].map((height, key) => ({ key, data: { height } })));
let nextKey = $state(3);
function add() {
items = [...items, { key: nextKey, data: { height: 100 } }];
nextKey += 1;
}
function grow() {
items = items.map(
(item, index) => index === 0
? { ...item, data: { height: item.data.height + 40 } }
: item
);
}
</script>
<style>
.tile {
display: grid;
align-content: center;
gap: 8px;
box-sizing: border-box;
padding: 12px;
border-radius: 8px;
background: var(--ant-color-primary-bg);
text-align: center;
overflow-wrap: anywhere;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<div class="controls">
<Button onclick={add}>{("Add card")}</Button>
<Button disabled={!items.length} onclick={() => { items = items.slice(0, -1); }}>
{("Delete last")}
</Button>
<Button disabled={!items.length} onclick={grow}>{("Enlarge first")}</Button>
</div>
<Masonry items={(items)} columns={(2)} gutter={12} fresh>
{#snippet itemRender(item)}
<div class="tile" style={`height:${item.data.height}px`}>{("Card ")}{(Number(
item.key
) + 1)}</div>
{/snippet}
</Masonry>
<output
aria-label={("Number of Masonry cards")}
>{(items.length)}</output>
Preferred column
column specifies the index from zero. As the number of columns decreases, the index is limited to the last available column.
<script lang="ts">
import { Masonry } from '@woodger/antd';
let columns = $state(3);
const items = [90, 130, 70, 110].map((height, key) => ({
key,
column: key === 0 ? 2 : undefined,
data: { height }
}));
</script>
<style>
.tile {
display: grid;
align-content: center;
gap: 8px;
box-sizing: border-box;
padding: 12px;
border-radius: 8px;
background: var(--ant-color-primary-bg);
text-align: center;
overflow-wrap: anywhere;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
label {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
</style>
<div
class="controls"
><label>{("Masonry Speakers ")}<select
bind:value={columns}
><option
value={2}
>2</option><option
value={3}
>3</option><option
value={4}
>4</option></select></label></div>
<Masonry items={(items)} columns={(columns)} gutter={12}>
{#snippet itemRender(item)}
<div class="tile" style={`height:${item.data.height}px`}>{(item.index + 1)}{(": column ")}{(item.column + 1)}</div>
{/snippet}
</Masonry>
Different axis spacing
Numeric pair specifies horizontal and vertical gutter in px. The control changes the geometry without recreating the data.
<script lang="ts">
import { Masonry } from '@woodger/antd';
const items = [90, 130, 70, 110, 150, 80].map((height, key) => ({ key, data: { height } }));
let horizontal = $state(12);
let vertical = $state(20);
</script>
<style>
.tile {
display: grid;
align-content: center;
gap: 8px;
box-sizing: border-box;
padding: 12px;
border-radius: 8px;
background: var(--ant-color-primary-bg);
text-align: center;
overflow-wrap: anywhere;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
label {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
</style>
<div class="controls">
<label>{("Horizontal gutter ")}<input
type="range"
min="0"
max="32"
bind:value={horizontal}
/><output>{horizontal}</output></label>
<label>{("Vertical gutter ")}<input
type="range"
min="0"
max="32"
bind:value={vertical}
/><output>{vertical}</output></label>
</div>
<Masonry items={(items)} columns={(2)} gutter={[horizontal, vertical]}>
{#snippet itemRender(item)}
<div class="tile" style={`height:${item.data.height}px`}>
{(item.index + 1)}
</div>
{/snippet}
</Masonry>
Semantic slots and provider
ConfigProvider.masonry sets the general design. The local function styles gets the allowed number of columns.
<script lang="ts">
import { ConfigProvider, Masonry } from '@woodger/antd';
const items = [90, 130, 70, 110, 150, 80].map((height, key) => ({ key, data: { height } }));
</script>
<style>
.tile {
display: grid;
align-content: center;
gap: 8px;
box-sizing: border-box;
padding: 12px;
border-radius: 8px;
background: var(--ant-color-primary-bg);
text-align: center;
overflow-wrap: anywhere;
}
</style>
<ConfigProvider masonry={{
styles: {
root: `
border: 1px dashed var(--ant-color-border);
border-radius: 8px;
`
}
}}>
<Masonry items={(items)} columns={(2)} gutter={12} classNames={{
item: 'custom-masonry-item'
}} styles={({ props }) => ({ item: `opacity:${props.columns === 2 ? 0.9 : 1}` })}>
{#snippet itemRender(item)}
<div class="tile" style={`height:${item.data.height}px`}>
{(item.index + 1)}
</div>
{/snippet}
</Masonry>
</ConfigProvider>
The same local class is used for different numbers of columns. Fresh updates the layout after changing the height, saving the editor.
Local and general prefix
Two numbers of columns with one local class; fresh styles, raw prefix in and saving the editor.
<script lang="ts">
import { Checkbox, ConfigProvider, Input, Masonry, type MasonryItemType } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
let tall = $state(false);
let draft = $state('');
const prefix = $derived(custom ? 'suite' : 'ant');
const items: MasonryItemType<{ height: number; title: string }>[] = [
{ key: 'draft', data: { height: 96, title: "Draft" } },
{ key: 'guide', data: { height: 64, title: "Manual" } },
{ key: 'api', data: { height: 80, title: 'API' } },
{ key: 'examples', data: { height: 72, title: "Examples" } }
];
</script>
<style>
.example {
display: grid;
gap: 20px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.tile {
display: grid;
box-sizing: border-box;
align-content: start;
gap: 8px;
min-width: 0;
padding: 12px;
border-radius: 8px;
background: var(--ant-color-fill-secondary);
overflow-wrap: anywhere;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("General prefix Masonry suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Masonry local prefix")}</Checkbox>
<Checkbox bind:checked={tall}>{("Enlarge card with prefix")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'masonry-theme' } }}>
<Masonry
items={(items)}
columns={(2)}
gutter={12}
fresh
class="prefix-masonry-main"
prefixCls={local ? 'project-masonry' : ''}
styles={({ props }) => ({
root: `outline: 1px ${props.prefixCls ? 'solid' : 'dashed'} var(--ant-color-primary-border)`
})}
>
{#snippet itemRender(item)}
<div class="tile" style={`height: ${item.key === 'draft'
&& tall ? 148 : item.data.height}px`}>
<span>{(item.data.title)}</span>
{#if item.key === 'draft'}
<Input bind:value={draft} aria-label={("Masonry draft with prefix")} />
{/if}
</div>
{/snippet}
</Masonry>
</ConfigProvider>
<ConfigProvider prefixCls="neighbor">
<Masonry items={(items.slice(1, 3))} columns={(1)} gutter={8}
class="prefix-masonry-neighbor" prefixCls={local ? 'project-masonry' : ''}>
{#snippet itemRender(item)}
<div
class="tile"
style={`height: ${item.data.height}px`}
>{(item.data.title)}</div>
{/snippet}
</Masonry>
</ConfigProvider>
<output
aria-label={("Prefix Masonry")}
>{("\n General: ")}{prefix}{("; class: ")}{(local ? 'project-masonry' : prefix + '-masonry')}
</output>
<p>
{("The same local class is used for different numbers of columns. Fresh updates the layout after changing the height, saving the editor.")}
</p>
</div>
Project cards
Initial review example with Card, adaptability and order change.
<script lang="ts">
import { Button, Card, Masonry } from '@woodger/antd';
const source = [120, 80, 160, 100, 140, 90].map((height, index) => ({
key: index,
data: { height, title: `Card ${index + 1}` }
}));
let reversed = $state(false);
let items = $derived(reversed ? [...source].reverse() : source);
</script>
<style>
.actions { margin-bottom: 16px; }
.masonry { min-height: 300px; }
</style>
<div class="actions">
<Button
onclick={() => { reversed = !reversed; }}
>{("Change card order")}</Button>
</div>
<div class="masonry">
<Masonry
items={(items)}
columns={({ xs: 1, sm: 2, lg: 3 })}
gutter={16}
fresh
>
{#snippet itemRender(item)}
<Card size="small" title={(item.data.title)} style={`height:${item
.data.height}px`}>{("\n Height ")}{(item.data.height)}px
</Card>
{/snippet}
</Masonry>
</div>
Thresholds Masonry parent
Inherited Masonry Thresholds
Reset Masonry Thresholds
Columns and both gutter axes read the global theme.token.screen*. Its sm/md thresholds are 640/900px; the nested area inherits them, inherit:false returns 576/768px. The sm query uses screenSM rather than screenSMMin. In the interval without matches, columns reverts to xs, intervals are resolved separately. Changing tokens saves the elements and the editor; with SSR, an empty root without cards remains.
Topic thresholds, columns and spacing
Global screen* tokens change columns and both gutter axes. Comparison of inheritance and inherit:false; saving cards, editor and nativeElement when updating thresholds.
Breakpoints.svelte<script lang="ts"> import { Checkbox, ConfigProvider } from '@woodger/antd'; import BreakpointMasonry from './BreakpointMasonry.svelte'; let custom = $state(true); let separateMinimum = $state(false); const token = $derived( custom ? { screenXSMax: 639, screenSMMin: 640, screenSM: separateMinimum ? 680 : 640, screenSMMax: 899, screenMDMin: 900, screenMD: separateMinimum ? 920 : 900 } : {} ); </script> <style> .example, .scopes { display: grid; gap: 24px; min-width: 0; } .controls { display: flex; flex-wrap: wrap; gap: 12px; } p { margin: 0; } </style> <div class="example"> <div class="controls"> <Checkbox bind:checked={custom}>{("Your Masonry thresholds")}</Checkbox> <Checkbox bind:checked={separateMinimum}> {("Separate screenSMMin and screenSM Masonry")} </Checkbox> </div> <ConfigProvider theme={{ cssVar: { prefix: 'responsive-masonry' }, token }}> <div class="scopes"> <BreakpointMasonry id="custom" title={("Thresholds Masonry parent")} /> <ConfigProvider> <BreakpointMasonry id="inherited" title={("Inherited Masonry Thresholds")} /> </ConfigProvider> <ConfigProvider theme={{ inherit: false }}> <BreakpointMasonry id="reset" title={("Reset Masonry Thresholds")} /> </ConfigProvider> </div> </ConfigProvider> <p> {("Columns and both gutter axes read the global theme.token.screen*. Its sm/md thresholds are 640/900px; the nested area inherits them, inherit:false returns 576/768px. The sm query uses screenSM rather than screenSMMin. In the interval without matches, columns reverts to xs, intervals are resolved separately. Changing tokens saves the elements and the editor; with SSR, an empty root without cards remains.")} </p> </div>BreakpointMasonry.svelte<script lang="ts"> import { Input, Masonry, type MasonryItemType } from '@woodger/antd'; let { id, title }: { id: string; title: string } = $props(); let draft = $state(("Draft")); let nativeElement = $state<HTMLDivElement>(); let columns = $state(0); const items: MasonryItemType<{ height: number }>[] = [112, 64, 96, 72, 88, 56] .map((height, key) => ({ key, data: { height } })); </script> <style> section { display: grid; gap: 12px; min-width: 0; padding: 16px; border-radius: 8px; background: var(--ant-color-bg-container); color: var(--ant-color-text); } .tile { display: grid; align-content: start; gap: 8px; box-sizing: border-box; min-width: 0; padding: 12px; border-radius: 8px; background: var(--ant-color-fill-secondary); overflow-wrap: anywhere; } h4 { margin: 0; } </style> <section id={`masonry-breakpoints-${id}`} aria-label={(title)}> <h4>{(title)}</h4> <form aria-label={("" + String((title)) + ": shape")} onsubmit={event => { event.preventDefault(); }}> <Masonry items={(items)} bind:nativeElement columns={({ xs: 1, sm: 2, md: 3 })} gutter={[{ xs: 0, sm: 12, md: 18 }, { xs: 4, sm: 8, md: 12 }]} onLayoutChange={layout => { columns = layout.length ? Math.max(...layout.map(item => item.column ?? 0)) + 1 : 0; }}> {#snippet itemRender(item)} <div class="tile" style={`height:${item.data.height}px`}> <span>{("Card ")}{(item.index + 1)}</span> {#if item.index === 0} <Input name="draft" aria-label={("" + String((title)) + ": draft")} bind:value={draft} /> {/if} </div> {/snippet} </Masonry> </form> <output aria-label={("" + String((title)) + ": speakers")} >{("Speakers: ")}{columns}</output> <output aria-label={("" + String((title)) + ": root")}>{(nativeElement ? "Connected" : "Waiting mount")}</output> </section>
API
Themes of the ant.design live page are mapped to the public API of the installed package. Full definitions of Props are in @woodger/antd.
| Theme | Example or limitation |
|---|---|
| CSS prefixes | Local classes, common namespace width and saving measured cells. |
| Basic | Height measurement and short columns. |
| Responsive | Columns and gutter by viewport. |
| Image | Loading images of different proportions. |
| Dynamic | Adding, deleting and fresh monitoring. |
| Custom semantic dom styling | Local functions and ConfigProvider.masonry. |
| Property | Description | Type | Default |
|---|---|---|---|
prefixCls | Full local prefix of root/item/motion classes. The empty string and undefined inherit the same prefix. styles/classNames get the original local prefix; The width service variable depends on ConfigProvider.prefixCls. | string | ConfigProvider + -masonry |
items | Unique key, data and optional children/column/height. | MasonryItemType<Data>[] | — |
itemRender | Svelte snippet; gets the original fields, index and calculated column. | Snippet<[MasonryRenderInfo<Data>]> | — |
columns | Positive integer or breakpoint map by theme.token.screen*. Tokens are inherited and change queries without remount. For map without a match, use xs, then 1. | number | GridResponsive<number> | 3 |
gutter | One numeric interval for both axes or a pair of horizontal and vertical. Each axis' responsive map uses global screen* theme thresholds. | GridGutter | [GridGutter, GridGutter] | 0 |
fresh | Continuous monitoring of the sizes of individual elements via ResizeObserver. | boolean | false |
onLayoutChange | Initial order of items with calculated column after measurement. | (items with column) => void | — |
classNames | Classes root/item, object or function. | MasonrySemantic<Data> | — |
styles | CSS lines root/item; the function receives props with columns enabled. | MasonrySemantic<Data> | — |
nativeElement | bind:nativeElement returns root after mount. | HTMLDivElement | — |
children | Compatible Props field; cells are specified through items, and not through general children. | MasonryContent | — |
MasonryItem
key - a unique string or number, uniqueness is checked after conversion to a string. column is the preferred index from zero. data stores application data; itemRender receives them along with index and column. height is adopted for compatibility, but does not replace the DOM dimension.
Semantic DOM
root is a div with a calculated height, item is a positioned cell. The visual distribution by columns does not change the original reading and keyboard order. ConfigProvider.masonry and local classNames/styles style root/item.
On SSR root is empty; items appear after mount, just like the original effect. If you require server-side content, select a different application composition. bind:nativeElement is cleared on unmount; The component removes observers and subscriptions on its own.
Registration tokens
Masonry does not have its own component tokens. The colors and font of the cards set the child components and the overall theme; root/item are styled using semantic styles. The layout and spacing are set by columns/gutter.
| Token | Current value |
|---|---|
motionDurationFast | 0.1s |
motionDurationSlow | 0.3s |
motionEaseOut | cubic-bezier(0.215, 0.61, 0.355, 1) |
FAQ
Why doesn't changing the height rearrange the layout?
For arbitrary content changes, enable fresh. Without it, the root, image loading and items changes are observed.
What takes precedence over itemRender?
item.children, except null/undefined. The general children of the cell component does not create.
Why doesn't height set the height of the card?
Layout measures DOM. Set the size of the content itself or use its natural height.
Is it possible to pass gutter as a CSS string?
The type allows this, but there is no string normalization in the geometry yet. Use a numeric interval or a responsive map of numbers.