Search code examples
csslayoutflexboxmasonry

Horizontal masonry layout with flexbox CSS only


I'm trying to create a horizontal masonry layout using only CSS and flexbox. The problem I'm having is there are vertical gaps between the elements, without using align-left: stretch; is it possible to close the gaps?

.card-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap; 
  align-items: flex-start;
}


.card {
  width: 25%;
  flex: 1 0 auto;
}

full codepen here


Solution

  • Here is one option using wrapped columns, but it requires a fixed height.

    .card-container {
      display: flex;
      flex-flow: column wrap;
      height:100vh;
      align-items: center;
      background-color: #888;
    }
    

    A better option for CSS masonry layout is to use columns, an example is on this blog post http://w3bits.com/css-masonry/

    .masonry { /* Masonry container */
        -moz-column-count: 4;
        -webkit-column-count: 4;
        column-count: 4;
        -moz-column-gap: 1em;
        -webkit-column-gap: 1em;
        column-gap: 1em;
    }
    
    .item { /* Masonry bricks or child elements */
        background-color: #eee;
        display: inline-block;
        margin: 0 0 1em;
        width: 100%;
    }