jpfaller93 jpfaller93 - 14 days ago 5
CSS Question

Flex-wrap: Same space between rows?

After a long time, I now have the possibility to work again with the css property

flex
.
The
justify-content: space-between;
works great, but now I'd like to have space between the rows too (which should be the same space as it is between the single boxes in a row – see image attached).

Is there any possibility to do this easily?

enter image description here

Answer

I'm not sure that you can achieve it with pure css. The easiest js would be something like this:

Click in Full page below the Code Snippet or test it in Codepen

function vertSpace() {
  var container = $("section"),
      containerWidth = container.outerWidth(),
      elem = container.find(".box"),
      elemWidth = elem.first().outerWidth(),
      num = Math.floor(containerWidth / elemWidth),
      space = (containerWidth - num*elemWidth) / (num - 1);
  elem.css("margin-bottom",space +"px") 
}

$(window).on("load resize",function(e){
  vertSpace();
});
* {
  box-sizing: border-box;
}

section {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-wrap: wrap;
      -ms-flex-wrap: wrap;
          flex-wrap: wrap;
  -webkit-box-pack: justify;
  -webkit-justify-content: space-between;
      -ms-flex-pack: justify;
          justify-content: space-between;
}
section .box {
  background-color: silver;
  -webkit-box-flex: 0;
  -webkit-flex: 0 0 20em;
      -ms-flex: 0 0 20em;
          flex: 0 0 20em;
  padding: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section>
  <div class="box">
    elem 1
  </div>
  <div class="box">
    elem 2
  </div>
  <div class="box">
    elem 3
  </div>
  <div class="box">
    elem 4
  </div>
  <div class="box">
    elem 5
  </div>
  <div class="box">
    elem 6
  </div>
  <div class="box">
    elem 7
  </div>
  <div class="box">
    elem 8
  </div>
  <div class="box">
    elem 9
  </div>
</section>