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
CSS masonry with flexbox, :nth-child(), and order. On the surface it seems fairly easy to create a masonry layout with flexbox; all you need to do is set flex-flow to column wrap and voilà, you have a masonry layout.
Grid and flexbox. The basic difference between CSS Grid Layout and CSS Flexbox Layout is that flexbox was designed for layout in one dimension - either a row or a column. Grid was designed for two-dimensional layout - rows, and columns at the same time.
Masonry layout is a layout method where one axis uses a typical strict grid layout, most often columns, and the other a masonry layout. On the masonry axis, rather than sticking to a strict grid with gaps being left after shorter items, the items in the following row rise up to completely fill the gaps.
Of course CSS grid and flexbox can work together in a layout. You can use flexbox inside CSS grid and vice versa. For instance, you could use flexbox to center an element like a button both vertically and horizontally within a particular grid cell (since centering with other CSS methods is … tricky).
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%;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With