Masonry
Masonry Style
by XcsN
HTML
<script src="https://rawgithub.com/desandro/masonry/master/jquery.masonry.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap-combined.min.css">
<script src="http://masonry.desandro.com/masonry.pkgd.min.js"></script>
<h1>Masonry - appended</h1>
<p><button id="append-button">Append new items</button>
<div class="masonry">
<div class="item w3"></div>
<div class="item h4"></div>
<div class="item h1"></div>
<div class="item h4"></div>
<div class="item h3"></div>
<div class="item h3"></div>
<div class="item h2"></div>
<div class="item h3"></div>
<div class="item h1"></div>
<div class="item h4"></div>
<div class="item h3"></div>
<div class="item h2"></div>
<div class="item h1"></div>
</div>
CSS
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body { font-family: sans-serif; }
.masonry {
background: #EEE;
max-width: 640px;
}
.masonry .item {
width: 60px;
height: 60px;
float: left;
background: #D26;
border: 2px solid #333;
border-color: hsla(0, 0%, 0%, 0.5);
border-radius: 5px;
}
.item.w2 { width: 120px; }
.item.w3 { width: 180px; }
.item.w4 { width: 240px; }
.item.h2 { height: 100px; }
.item.h3 { height: 130px; }
.item.h4 { height: 180px; }
button {
font-size: 20px;
}
JavaScript
// http://masonry.desandro.com/masonry.pkgd.js added as external resource
// create <div class="item"></div>
function getItemElement() {
var elem = document.createElement('div');
var wRand = Math.random();
var hRand = Math.random();
var widthClass = wRand > 0.92 ? 'w4' : wRand > 0.8 ? 'w3' : wRand > 0.6 ? 'w2' : '';
var heightClass = hRand > 0.85 ? 'h4' : hRand > 0.6 ? 'h3' : hRand > 0.35 ? 'h2' : '';
elem.className = 'item ' + widthClass + ' ' + heightClass;
return elem;
}
docReady( function() {
var container = document.querySelector('.masonry');
var button = document.querySelector('#append-button');
var msnry = new Masonry( container, {
columnWidth: 60
});
eventie.bind( button, 'click', function() {
// create new item elements
var elems = [];
var fragment = document.createDocumentFragment();
for ( var i = 0; i < 3; i++ ) {
var elem = getItemElement();
fragment.appendChild( elem );
elems.push( elem );
}
// append elements to container
container.appendChild( fragment );
// add and lay out newly appended elements
msnry.appended( elems );
});
});