Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting vertical gaps between flex items

Tags:

html

css

flexbox

If this is our code, it creates 4 boxes in each row, with an equal vertical space between them , but there are two problems that I don't know how to fix:

  1. Boxes in the last row should be adjusted to the left.

  2. There should be 20px vertical space between boxes.

How can I do that with flexbox?

.wrapper {
  max-width: 80%;
  margin: 20px auto 0;
  display: flex;
  flex-flow: wrap;
  justify-content: space-between;
  /* justify-content: flex-start; */
}

.box {
  flex-basis: 23%;
  height: 100px;
  outline: 1px solid black;
  background-color: #ccc;
  margin-bottom: 20px;
}
<div class="wrapper">

  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>

</div>
like image 763
user1941537 Avatar asked Apr 09 '19 00:04

user1941537


2 Answers

Try this:

.wrapper{
  justify-content: flex-start;
}
.box {
  flex-basis: 23%;
  margin-right: 2%;
  margin-bottom: 20px;
}

Idea is: 23% + 2% = 25% so there will be 4 objects per line unless you restrict min-width. But the layout is still justify-content: flex-start;

like image 59
DeeZee Avatar answered Sep 17 '22 12:09

DeeZee


I have posted updated code. Please check if it works for you.

.wrapper {
  max-width: 80%;
  margin: 20px auto 0;
  display: flex;
  flex-flow: wrap;
  /*justify-content: space-between;*/
  justify-content: flex-start; 
}

.box {
  flex: 0 0 23%;
  max-width: 23%;
  margin-left: 1%;
  margin-right: 1%;
  height: 100px;
  outline: 1px solid black;
  background-color: #ccc;
  margin-bottom: 20px;
}
<div class="wrapper">

  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>

</div>
like image 32
Rhythm Ruparelia Avatar answered Sep 17 '22 12:09

Rhythm Ruparelia