Build a masonry grid in Angular
Masonry layouts are useful anywhere you have items with different heights but still want a compact, flowing grid. Common examples include: Photo and image galleries — images naturally have different aspect ratios. Dashboards — KPI cards, charts, tables, and widgets rarely have the same height. Product and catalog pages — product descriptions and images can vary in size. Blog and content feeds —…
Masonry layouts are helpful for displaying items with varying heights in a compact, flowing grid format. They are well-suited for photo galleries, dashboards, product pages, blog feeds, portfolio grids, search results, admin interfaces, and analytics dashboards. Unlike normal CSS grid layouts that accommodate taller items in rows, masonry layouts place each item in the column with the least available height.
To build a masonry grid in Angular, start by installing the masonry-angular library using npm. It supports Angular 17.1 and later, including Angular 22. Once installed, import the masonry directives into your component and define the grid structure using the masonry-grid container and masonryGridItem child identifier. Specify the desired number of columns and gutter spacing.
Avoid assigning fixed widths to the grid items, as the library calculates them itself. You can style the items normally while letting the grid handle the width. To make the grid responsive, use the columnWidth property, which automatically adjusts the number of columns based on the screen size. You can also define explicit column counts for specific breakpoints or use named breakpoints for better readability.
By leveraging masonry-angular, you can create a responsive, dynamic masonry grid that avoids layout jumps when items load, supports spanning, works with Angular server-side rendering (SSR), and can utilize native CSS masonry where available.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.