24

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

Julian
  • 920
  • 1
  • 11
  • 23

2 Answers2

21

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%;
}
user2548213
  • 356
  • 1
  • 4
  • 1
    I like your solutions! I was assuming the blocks had to flow from left to right. In your case they flow from top to bottom. – joerideg May 19 '15 at 09:25
  • 34
    Columns is not a better solution as columns make the newest items go down the left column as opposed to the newest items being listed left right and then going down – comu Dec 22 '15 at 21:08
  • This is the solution to the problem ( CSS, no vertical spacing, masonry layout) https://stackoverflow.com/a/25668648/871781 – JoeCodeCreations Oct 03 '17 at 22:24
19

Flex box wrap wraps the overflowing elements to a new row. This new row has, just like the previous row, the height of the highest flex child in it. It will not let the elements in the row go outside that rows boundaries.

So unfortunately, no you cannot close the vertical gaps with flexbox.

Roman Starkov
  • 52,420
  • 33
  • 225
  • 300
joerideg
  • 1,748
  • 1
  • 12
  • 18