THIS IS A SELF Q&A
Often my creative director's ask to build a Masonry powered grid, but to make it responsive. Then new version of Masonry can do this, but with variable height images, the initial layout looks broken. The solution is the imagesLoaded plugin, but it's not immediately clear the best way to apply this to a grid, specially if that grid is generated by a CMS (WordPress in my case).
So my questions is, how best to make a responsive Masonry grid, that is 3 colomns wide, and looks good on initial load.
For a 3 column responsive grid, with 25px gutter around each block. I this possible to make this gutter responsive/variable too.
Obviously you need to include the Masonry and imagesLoaded JS files on your page.
Your HTML would be something like this:
<div class="grid">
<div class="block">
<img src="example.jpg">
</div>
</div>
Your CSS would be this:
.block {
float: left;
margin-bottom: 25px;
width: calc(33.33% - 17px);
opacity: 0;
}
.block img {
width: 100%;
height: auto;
}
And the JS would be something like this:
jQuery(document).ready(function(){
// Init Masonry
var opts = {
itemSelector: '.block',
columnWidth: '.block',
gutter: 25,
percentPosition: true,
transitionDuration: 0
}
var $grid = jQuery('.grid').masonry(opts);
// Position and show image as it loads
jQuery('.grid').imagesLoaded().progress(function(imgLoadData, elem ){
jQuery(elem.img).closest('.block').css('opacity', 1);
$grid.masonry('layout');
});
});