How to Create Grid/Tile View? [duplicate]
Solution 1:
This type of layout is called Masonry layout. Masonry is another grid layout but it will fill out the whitespace caused by the difference height of elements.
jQuery Masonry is one of jQuery plugin to create masonry layout.
Alternatively, you can use CSS3 column
s. But for now jQuery based plugin is the best choice since there is compatibility issue with CSS3 column.
Solution 2:
You can use flexbox.
-
Place your elements in a multiline column flex container
#flex-container { display: flex; flex-flow: column wrap; }
-
Reorder the elements, so that the DOM order is respected horizontally instead of vertically. For example, if you want 3 columns,
#flex-container > :nth-child(3n + 1) { order: 1; } /* 1st column */ #flex-container > :nth-child(3n + 2) { order: 2; } /* 2nd column */ #flex-container > :nth-child(3n + 3) { order: 3; } /* 3rd column */
-
Force a column break before the first item of each column:
#flex-container > :nth-child(-n + 3) { page-break-before: always; /* CSS 2.1 syntax */ break-before: always; /* New syntax */ }
Sadly, not all browsers support line breaks in flexbox yet. It works on Firefox, though.
#flex-container {
display: flex;
flex-flow: column wrap;
}
#flex-container > :nth-child(3n + 1) { order: 1; } /* 1st column */
#flex-container > :nth-child(3n + 2) { order: 2; } /* 2nd column */
#flex-container > :nth-child(3n + 3) { order: 3; } /* 3rd column */
#flex-container > :nth-child(-n + 3) {
page-break-before: always; /* CSS 2.1 syntax */
break-before: always; /* New syntax */
}
/* The following is optional */
#flex-container > div {
background: #666;
color: #fff;
margin: 3px;
display: flex;
justify-content: center;
align-items: center;
font-size: 36px;
}
#flex-container > :nth-child(1) { height: 100px; }
#flex-container > :nth-child(2) { height: 50px; }
#flex-container > :nth-child(3) { height: 75px; }
#flex-container > :nth-child(4) { height: 50px; }
#flex-container > :nth-child(5) { height: 100px; }
#flex-container > :nth-child(6) { height: 50px; }
#flex-container > :nth-child(7) { height: 100px; }
#flex-container > :nth-child(8) { height: 75px; }
#flex-container > :nth-child(9) { height: 125px; }
<div id="flex-container">
<div>1</div><div>2</div><div>3</div>
<div>4</div><div>5</div><div>6</div>
<div>7</div><div>8</div><div>9</div>
</div>