A masonry layout is when the elements of a grid don’t have regular sizes but the grid itself fits them up in the optimal position and size. There are actually plenty of ways to achieve a masonry layout, on this occasion we’ll be using a library called Muuri1Haltu. Muuri, Responsive, sortable, filterable and draggable grid layouts.

First, to download the library or use the CDN you can check out the references at the end of the post. Once you have it link it on your HTML.

Second, according to Muuri’s documentation2Haltu. 2015. Muuri’s documentation. GitHub, it’s necessary to keep the following structure

<!-- The content of our grid -->
<div class="grid">

  <!-- We'll have as many .item as we want -->
  <div class="item">
    <div class="item-content">
      <!-- Content here -->
    </div>
  </div>

</div>

In our case, the HTML would look like this:

<script src="https://unpkg.com/muuri@0.8.0/dist/muuri.min.js"></script>
<div class="container">
  <div class="grid" id="grid">

    <div class="item">
      <div class="item-content">
        <img src="image1" alt="description">
      </div>
    </div>

    <div class="item">
      <div class="item-content">
        <img src="image2" alt="description">
      </div>
    </div>

  </div> 
</div>

Remember that we can have as many images as we want to have.

After that, in the CSS you only need to set the positions of the grid as relative and item as absolute. Moreover, we’re going to adjust the width of the items and add a media query to make it change from a three-column grid to a two-column grid.

As a result, this would be the container and the grid:

.container{
  padding-top: 35px;
  padding-bottom: 10px;
  width: 90%;
  max-width: 900px;
  margin: auto;
}

.grid{
    position: relative;
    width: 100%;
}

This would be the item and its content. On Muuri the content can be anything but in this case, is just an image.

.item{
    position: absolute;
    display: block;
    padding: 0;
    margin: 10px;
    width: calc(33.3333% - 20px);
}

.item-content{
    position: relative;
}

img{
    width: 100%;
}

And this is the media query:

@media screen and (max-width: 600px){
    .item{
        width: calc(50% - 20px);
    }
}

Finally, in order to init the library we need to add this line of javascript:

const grid = new Muuri('#grid');

This is the masonry with Muuri finished, check it out on 1x and 0.5x scale for the auto adjustment

See the Pen Simple Masonry with muuri by Dager (@dagerzuga) on CodePen.dark


All the photos of this project are from Unsplash.

References   [ + ]