Components Cards & Layout MasonryGrid

MasonryGrid

Pure CSS multi-column masonry layout.

Live demo

01
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6
Item 7
Item 8

Implementation

02
MasonryGrid.svelte
<MasonryGrid columns={3} gap="1rem">
  {#each items as item}
    <div class="item">{item}</div>
  {/each}
</MasonryGrid>

Logic explainer

03

What Does It Do? (Plain English)

A pure CSS masonry layout component that arranges items in optimal vertical columns (like Pinterest), without requiring JavaScript to calculate heights or positions.

How It Works (Pseudo-Code)

.masonry-grid {
  column-count: var(--cols);
  column-gap: var(--gap);
}
.masonry-grid > * {
  break-inside: avoid;
  margin-bottom: var(--gap);
}

Uses CSS multi-column layout. Items automatically flow into columns and break-inside: avoid ensures items don't get split across columns.

State Flow Diagram

stateDiagram-v2
    [*] --> Render
    Render --> ColumnsFlow : Browser handles layout natively
    ColumnsFlow --> [*]

Props Reference

  • columns (number | string): The number of columns. Default: 3.
  • gap (string): The gap between items and columns. Default: '1rem'.
  • class (string): Additional CSS classes.

Edge Cases

  • Source Order vs Visual Order: CSS columns flow top-to-bottom, then left-to-right. Keyboard navigation follows source order (top-to-bottom per column), which is usually acceptable for masonry.
  • Dynamic Content: Works perfectly with dynamically loaded images since it relies on native CSS reflows instead of JS math.

Dependencies

  • None. Pure Svelte 5 and CSS multi-column layout.

File Structure

  • src/lib/components/MasonryGrid.svelte
  • src/lib/components/MasonryGrid.md