Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS Flexbox's `justify-content:space-between` but left-aligning last row [duplicate]

Tags:

css

flexbox

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.

like image 394
JVG Avatar asked Aug 25 '15 13:08

JVG


1 Answers

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>
like image 130
vals Avatar answered Oct 23 '22 03:10

vals