Creating Brick-like Layouts with masonry in CSS

Firefox is also the only browser that currently supports masonry-style grid layouts. It’s still experimental at this stage. You’ll need to enable it by changing the value of layout.css.grid- tempLate-masonry-vaLue.enabLed to true . You can find this option in Firefox’s about:config menu.

Masonry-style layouts, also known as Pinterest-style layouts, until now have required a JavaScript library such as Masonry.js . With the masonry grid template value, creating masonry-style layouts requires much less effort:

.grid {

display: grid;

gap: 1rem;

/* Short hand for grid-template-rows / grid-template-columns */

grid-template: masonry / repeat(6, 1fr);

}

This creates the layout shown in the image below.

Rather than add strict tracks for rows (when grid-template-rows: masonry ) or columns (when grid-template-rows: masonry ), masonry creates a tightly packed layout.

Grid items shrink to the dimensions of their content. By default, they’re arranged where there’s available space, which may not match the source order. However, we can change this behavior using the masonry-auto-flow property. For example, adding masonry-auto-flow: next to the grid container forces items to be arranged in order, as pictured below, where masonry-auto-fLow: next preserves the order of grid items in a masonry layout.

To experiment with masonry while ensuring backward compatibility, separate your grid- tempLate-rows and grid-tempLate-coLumns values. Remember: if a browser can’t parse a declaration, that declaration gets discarded. Using grid-template for both values would make the entire rule fail. Instead, set grid-template-rows or grid-template-columns to masonry , and use the other property to define grid tracks:

.grid {

display: grid;

gap: 1rem;

grid-template-columns: repeat(6, 1fr);

grid-template-rows: masonry;

}

In browsers that don’t yet support the masonry value, the CSS above creates a six-column grid layout. For 12 grid items, you’d see two rows.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *