Masonry

Cascading grid layout library

What is Masonry?

Masonry is a JavaScript grid layout library. It works by placing elements in optimal position based on available vertical space, sort of like a mason fitting stones in a wall. You’ve probably seen it in use all over the Internet.

Install

A packaged source file includes everything you need to use Masonry.

Bower

If you are familiar with the command line and build processes, Masonry can be installed with Bower. Masonry is built on dependencies. Bower takes care of these.

bower install masonry

Getting started

HTML

Masonry works on a container element with a group of similar child items.

<div id="container">
  <div class="item">...</div>
  <div class="item w2">...</div>
  <div class="item">...</div>
  ...
</div>

Include the Masonry script in your site.

<script src="/path/to/masonry.pkgd.min.js"></script>

CSS

All sizing of items is handled by your CSS.

.item { width: 25%; }
.item.w2 { width: 50%; }

Initialize with JavaScript

Initialize a Masonry instance with new Masonry( element, options ). The Masonry constructor accepts two arguments: the container element and an options object.

var container = document.querySelector('#container');
var msnry = new Masonry( container, {
  // options
  columnWidth: 200,
  itemSelector: '.item'
});

The element can be a selector string for a single element.

var msnry = new Masonry( '#container', {
  // options
});

Initialize in HTML

You can initialize Masonry in HTML, without writing any JavaScript. Add js-masonry to the class of the container element. Options can be set with a data-masonry-options attribute.

<div id="container" class="js-masonry"
  data-masonry-options='{ "columnWidth": 200, "itemSelector": ".item" }'>

Options set in HTML must be valid JSON. Keys need to be quoted, for example "itemSelector":. Note that the attribute value uses single quotes ', but the JSON entities use double-quotes ".

That’s it! Now let’s do some fun stuff with options and methods.

jQuery

jQuery is not required to use Masonry. But if you do enjoy jQuery, Masonry works with it as a jQuery plugin.

var $container = $('#container');
// initialize
$container.masonry({
  columnWidth: 200,
  itemSelector: '.item'
});

Get the Masonry instance with .data('masonry').

var msnry = $container.data('masonry');

imagesLoaded

Unloaded images can throw off Isotope layouts and cause item elements to overlap. imagesLoaded resolves this issue. Read more about using imagesLoaded with Masonry.

MIT License

Masonry is released under the MIT License. Have at it.