JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.2/masonry.pkgd.min.js"></script>
<input type="hidden" name="hfTotalGridItems" id="hfTotalGridItems" value="10" />
<div class="grid">
<div class="item">
<div>lorem</div>
</div>
<div class="item">
<div>lorem</div>
</div>
<div class="item">
<div>lorem</div>
</div>
<div class="item">
<div>lorem</div>
</div>
<div class="item">
<div>lorem</div>
</div>
<div class="item">
<div>lorem</div>
</div>
<div class="item">
<div>lorem</div>
</div>
<div class="item">
<div>lorem</div>
</div>
<div class="item">
<div>lorem</div>
</div>
<div class="item">
<div>lorem</div>
</div>
</div>
<div class="result"></div>
CSS
.grid {
margin: 0 auto;
}
.item {
margin-bottom: 20px;
border: 1px solid red;
height: 80px;
width: 80px;
}
.filler {
background-color: #999;
border: 1px solid blue;
}
JavaScript
$(function () {
function calculateRows() {
var lisInRow = 0;
var $item = $('.grid .item');
var $grid = $('.grid');
var itemWidth = $('.grid .item').width();
var itemHeight = $('.grid .item').height();
$item.each(function () {
if ($(this).prev().length > 0) {
if ($(this).position().top != $(this).prev().position().top) return false;
lisInRow++;
} else {
lisInRow++;
}
});
var lisInLastRow = $item.length % lisInRow;
if (lisInLastRow == 0) lisInLastRow = lisInRow;
$('.result').html('No: of lis in a row = ' + lisInRow + '<br>' + 'No: of lis in last row = ' + lisInLastRow);
if (lisInLastRow < lisInRow) {
var $clonedItem = $('.grid .item:last-child').clone().empty().css({
width: itemWidth,
height: itemHeight
}).addClass('filler');
$grid.append($clonedItem).masonry('appended', $clonedItem);
} else {
if (newTotal > $('#hfTotalGridItems').val()) {
$grid.masonry('remove', $('.grid .item.filler'));
$grid.masonry();
}
}
}
var $grid = $('.grid');
$grid.masonry({
itemSelector: '.item',
isFitWidth: true,
gutter: 20
});
$grid.masonry('on', 'layoutComplete', function (event) {
calculateRows(event.length);
});
$grid.masonry();
});