5

I have a simple grid of boxes that I would like to responsively space with Flexbox.

The number of boxes is generated by the user, so I need something to work dynamically. Here's a codepen snippet of where I'm at:

<div class="wrap">
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
</div>

CSS:

.wrap{
  display:flex;
  flex-wrap:wrap;
  justify-content:space-between;
}

.thumb{
  width:150px;
  height:150px;
  background-color:black;
  margin-bottom:20px;
}

Here's what it looks like with the code above:

Flexbox last line left-align

Here's what I'd like it to look like:

enter image description here

How can this be achieved with flexbox? I want to avoid % margins and let flexbox do all the work here if possible as it works really nicely in a responsive setting.

JVG
  • 20,198
  • 47
  • 132
  • 210
  • Nope...not possible...it's come up before and the top row is not alignable like that. – Paulie_D Aug 25 '15 at 13:23
  • You mean the bottom row @Paulie_D? That's disappointing, have been googling around and can't find any discussion. Any proposed workarounds? – JVG Aug 25 '15 at 13:24
  • No, you can get the last row to do that **but** not with the alignment of the top row as well. – Paulie_D Aug 25 '15 at 13:25

1 Answers1

1

Well, you can do it, but at the expense of spoiling a little bit the DOM. Insert filler elements (as many as the maximum number elements that will fit in a row) with a height of 0, and you have it

.wrap{
  display:flex;
  flex-wrap:wrap;
  justify-content:space-between;
}

.thumb{
  width:150px;
  height:150px;
  background-color:black;
  margin-bottom:20px;
}


.filler{
  width:150px;
  height:0px;
  margin: 0px;
}
<div class="wrap">
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="thumb"></div>
  <div class="filler"></div>
  <div class="filler"></div>
  <div class="filler"></div>
  <div class="filler"></div>
  <div class="filler"></div>
  <div class="filler"></div>
  <div class="filler"></div>
  <div class="filler"></div>
  <div class="filler"></div>
</div>
vals
  • 61,425
  • 11
  • 89
  • 138