Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal masonry layout with flexbox CSS only [duplicate]

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

like image 461
Julian Avatar asked Feb 23 '15 19:02

Julian


People also ask

How do you make a masonry layout in CSS flexbox?

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.

Is CSS grid identical to flexbox?

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.

How do you make a masonry layout in CSS?

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.

Can you mix grid and flexbox?

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).


2 Answers

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%;
}
like image 87
user2548213 Avatar answered Oct 31 '22 16:10

user2548213


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.

like image 40
joerideg Avatar answered Oct 31 '22 16:10

joerideg