Although there are several plugins available to arrange your posts or image gallery using the masonry technique, it’s surprisingly easy to achieve the same result starting from scratch. Here’s a very simple implementation:

Download masonry.​pkgd.​min.js from masonry.desandro.com and add it to your theme.

Add the following to your header (or footer) changing the path to the script as necessary:

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/scripts/masonry.pkgd.min.js"></script>
<script>
$( window ).load( function()
{
$( '.grid' ).masonry( { itemSelector: '.grid-item' } );
$( '.gallery' ).masonry( { itemSelector: '.gallery-item' } );
});
</script>

Use .grid on a containing div and .grid-item on each item. There are lots of ways to do this – here how it looks if you’re using Posts on a Page.

<div class="grid"> 
<?php $catname = get_the_title(); ?> <?php global $post; $myposts = get_posts ('numberposts=10&orderby=menu_order&category_name=' . $catname ); foreach($myposts as $post) : setup_postdata($post); ?> 
<div class="grid-item">
<h3><?php the_title(''); ?></h3> 
<?php the_content(''); ?> 
<!-- you can put other stuff here as well --> 
</div><!-- end .grid-item --> 
<?php endforeach; ?> 
</div><!-- end .grid -->

There are lots of options available with the masonry script, but it’s quite easy to use CSS to tweak the layout. For example, here’s the CSS for a simple four column responsive layout:

.grid {
width: 101%;
overflow: hidden;
}
.grid-item {
 width: 24%;
 margin:0 1% 10px 0;
 }

You can use also media queries to change the number of columns depending on browser width.

Including .gallery and .gallery-item in the script function and adding the appropriate CSS allows the masonry effect to be applied to the native gallery.