Step-by-step Guide to Building a Masonry Layout with Css Grid

Creating a masonry layout with CSS Grid is an excellent way to display content in a dynamic and visually appealing manner. Unlike traditional grid layouts, masonry allows items to fit together like bricks in a wall, optimizing space and creating a modern look.

Understanding Masonry Layouts

A masonry layout arranges items in a grid where elements are positioned based on available space, rather than strict rows and columns. This results in a staggered, brick-like appearance, perfect for portfolios, galleries, or blog posts.

Step 1: Setting Up the HTML Structure

First, create a container element that will hold all your items. Each item inside this container will be styled to fit into the masonry layout.

Example HTML:

<div class=”masonry”>

<div class=”item”>Content 1</div>

<div class=”item”>Content 2</div>

<div class=”item”>Content 3</div>

<div class=”item”>Content 4</div>

</div>

Step 2: Applying CSS Grid Styles

Use CSS Grid to define the layout. Set the container to display as grid and specify the columns. To achieve the masonry effect, use grid auto-rows and grid row span.

Example CSS:

.masonry {

display: grid;

grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));

grid-auto-rows: 10px;

gap: 10px;

}

.item {

background-color: #eee;

border: 1px solid #ccc;

padding: 10px;

grid-row: span var(–span);

}

Step 3: Dynamic Row Spanning with JavaScript

To make items span multiple rows based on their height, you can use JavaScript to calculate and set the span dynamically.

Example JavaScript:

const items = document.querySelectorAll(‘.item’);

items.forEach(item => {

const height = item.offsetHeight;

const span = Math.ceil(height / 10); // 10 is grid-auto-rows value

item.style.setProperty(‘–span’, span);

});

Conclusion

Building a masonry layout with CSS Grid involves setting up a grid container, defining the grid properties, and dynamically adjusting item spans. This approach creates a flexible and modern layout suitable for various content types.