CSS Layout How to - Create Pure CSS Masonry Layout for Images using column








Question

We would like to know how to create Pure CSS Masonry Layout for Images using column.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
body {<!--   ww  w. j  ava  2  s  .co m-->
  padding: 5px;
}
/* (item margins = 5) */
.masonry {
  -webkit-column-width: 150px;
  -moz-column-width: 150px;
  column-width: 150px;
  /* same with bottom margin for the items */
  -webkit-column-gap: 5px;
  -moz-column-gap: 5px;
  column-gap: 5px;
}

.masonry img {
  display: block;
  /* expand! */
  width: 100%;
  height: auto;
  background-color: silver;
  /* bottom margin */
  margin: 0 0 5px 0;
}
</style>
</head>
<body>
  <div class='masonry'>
    <img alt="" width="150" height="200" src="http://lorempixel.com/150/200/animals/1" /> 
    <img alt="" width="150" height="250" src="http://lorempixel.com/150/250/animals/2" /> 
    <img alt="" width="150" height="200" src="http://lorempixel.com/150/200/animals/3" /> 
    <img alt="" width="150" height="150" src="http://lorempixel.com/150/150/animals/4" /> 
    <img alt=""  width="150" height="100" src="http://lorempixel.com/150/100/animals/5" /> 
    <img alt="" width="150" height="100" src="http://lorempixel.com/150/100/animals/6" /> 
    <img alt="" width="150" height="100" src="http://lorempixel.com/150/100/animals/7" /> 
    <img alt=""  width="150" height="100" src="http://lorempixel.com/150/100/animals/8" /> 
    <img alt="" width="150" height="200" src="http://lorempixel.com/150/200/animals/9" /> 
    <img alt="" width="150" height="250" src="http://lorempixel.com/150/250/food/1" />
    <img alt="" width="150" height="150" src="http://lorempixel.com/150/150/food/2" /> 
    <img alt="" width="150" height="100" src="http://lorempixel.com/150/100/food/3" />
    <img alt="" width="150" height="100" src="http://lorempixel.com/150/100/food/4" /> 
    <img alt="" width="150" height="150" src="http://lorempixel.com/150/150/food/5" />
    <img alt="" width="150" height="200" src="http://lorempixel.com/150/200/food/6" /> 
    <img alt="" width="150" height="150" src="http://lorempixel.com/150/150/food/7" />
    <img alt="" width="150" height="150" src="http://lorempixel.com/150/250/food/8" />
  </div>
</body>
</html>

The code above is rendered as follows: