3

I have dynamic content flowing into a two-column grid. Flex box is a nice solution, but it forces the rows to be the same height, creating some awkward white space when one has more content. Does anyone know of a lightweight solution that can achieve what is hopefully clearly communicated in the below image?

Code for my current solution:

.grid-container {
  display:flex;
  flex-wrap: wrap;
  justify-content:space-between;
  height:auto;
  height:700px;
  overflow-y:scroll;
}
.contained-cell{
  width:48.5%;
  padding:40px 20px;

enter image description here

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
mlaugh4
  • 87
  • 2
  • 8
  • this is what helped me(if you are using Bootstrap) https://stackoverflow.com/questions/52668233/bootstrap-grid-uneven-columns – Vlad Misaila Sep 07 '22 at 17:25

1 Answers1

2

In your code, the flex items are aligned in a row by default (flex-direction: row). And also by default, flex items will stretch to occupy the full available height of the container (align-items: stretch) – thus creating equal height columns.

You could use align-items: flex-start to make each flex item stretch only enough to contain its content. But then, as you've noted, this doesn't change the height of the row, and the result is lots of vertical white space between items.

The standard solution for this layout is jQuery Masonry which, as they write on their website, works by placing elements in optimal position based on available vertical space, sort of like a mason fitting stones in a wall. That's one option.

Keeping to CSS, however, another flexbox solution is changing the flex-direction from row to column. With this set-up, equal height rows don't apply, vertical whitespace isn't an issue, and each flex item can be its own height.

Here's a demo: http://jsfiddle.net/8rq0maL4/1/

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    I was hoping to avoid Masonry, but it's seeming more like that's the way to go, especially considering that I'd like to order in a Z-pattern (top-left --> top-right --> [down a row]-left --> etc). Thanks so much, Michael! – mlaugh4 Nov 05 '15 at 21:37