Pure CSS masonry layout

Pure CSS masonry layout

How to create a masonry layout using only CSS.

My question is: do we actually need JavaScript or a jQuery plugin to create a masonry layout? Well, it depends. If you want a pixel-perfect solution, then JavaScript is the right solution. But if you want something simpler but effective, then you should consider using CSS.

CSS3 columnar layout has been around for several years now but only with the latest browser generation we can get consistent results. We can use CSS columns to create our masonry layout.

To start with, we need a wrapper with several boxes inside:


<div id="container" class="cols">
    <div class="box one"></div>
    <div class="box two"></div>
    <div class="box one"></div>
    <div class="box three"></div>
    <div class="box two"></div>
    <div class="box five"></div>
    <div class="box one"></div>
    <div class="box two"></div>
    <div class="box six"></div>
    <div class="box three"></div>
    <div class="box two"></div>
</div>

Then we can create our columns with the column-count, column-width and column-gap properties:


#container {
    width: 100%;
    max-width: 700px;
    margin: 2em auto;
}
.cols {
    -moz-column-count:3;
    -moz-column-gap: 3%;
    -moz-column-width: 30%;
    -webkit-column-count:3;
    -webkit-column-gap: 3%;
    -webkit-column-width: 30%;
    column-count: 3;
    column-gap: 3%;
    column-width: 30%;
}
.box {
    margin-bottom: 20px;
}
.box.one {
    height: 200px;
    background-color: #d77575;
}
.box.two {
    height: 300px;
    background-color: #dcbc4c;
}
.box.three {
    background-color: #a3ca3b;
    height: 400px;
}
.box.four {
    background-color: #3daee3;
    height: 500px;
}
.box.five {
    background-color: #bb8ed8;
    height: 600px;
}
.box.six {
    background-color: #baafb1;
    height: 200px;
}

[view-example url="http://jsfiddle.net/gabrieleromanato/tQANc/"]