Product Design Lessons

Intro to Foundation  |   Lesson #65

Make a Masonry Grid Responsive

Learn to make masonry grids adapt to different size screens.

We're used to thinking of grids as blocks — a.k.a. "columns" — within rows. HTML and CSS lend themselves to this layout strategy, and users have come to expect the patterns that have become standard. But standard can get boring.

We won't claim that Pinterest's popularity came from its unusual yet functional "masonry" layout, but it sure stands out. Trouble is, six columns of masonry works fine on desktop, but looks awful on mobile devices.

But we found a simple way to make masonry layouts responsive. And like any pattern, it can be repeated. Here's how to create a masonry-style layout with Foundation's block grid and a little extra JS.

1. Add Masonry JS to your project

This technique uses Masonry JS, developed by David DeSandro. Download the code and drop masonry.pkgd.min.js into your project's JS folder.

Then add this to the bottom of your HTML file:

<script src="js/masonry.js"></script>

2. Set up the style

We're going to add a little CSS to see the blocks — for testing purposes only. Apply your own style later.

#container > li {
border: 1px solid red; /* !test */
}

3. Write the HTML

The HTML is straightforward. One container with an ID of "masonry-container" holds many "bricks," or items within the parent. Fill the bricks with bits of pictures and text.

<ul id="masonry-container" class="small-block-grid-2 medium-block-grid-4 large-block-grid-6">
<li>
<p>aaa</p>
<p>bbb</p>
<p>ccc</p>
<p>ddd</p>
</li>

<li>

<p>aaa</p>
<p>bbb</p>
<p>ccc</p>
<p>ddd</p>
</li>

</ul>

4. Initialize Masonry JS

Finally, it's time to turn on the grid. Add this to your HTML:

$(window).load(function(){
  $('#container').masonry({
    itemSelector: '#container li'
  });
});

How this works

Combined with Foundation's Block Grid, adjusting the grid is a snap. Use combinations of small- medium- and large-block-grid-x to make the masonry layout adjust for different browser windows.

This turns a regular block grid into a well-fit masonry grid. Download the complete sample (and remember to get the JS from the source).


About the instructor

Ben

Ben Gremillion is a Design Writer at ZURB. He started his career in newspaper and magazine design, saw a digital future, and learned HTML in short order. He facilitates the ZURB training courses.