2

Hello I have a simple grid using flex. Works fine but my issue is when theres not enough elements to fit the row, it spaces the elements out to the edges.

For example, when I have a row to fit 3 items per row and have a total of 5 items, the bottom row will have the two elements on the edges with a gap in the middle.

Heres my code:

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

.grid div {
  flex-basis: 26%;
  height: 50px;
  background-color: red;
  margin-bottom: 20px;
}
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

As you can see, theres a gap in the bottom row. Is there a flex method to push everything to the left while keeping the justify-content: space-between?

I could just give margin right to everything but nth child 3n but I was wondering if theres a better flexy way to do it.

Thanks!

splash
  • 12,817
  • 1
  • 42
  • 65
cup_of
  • 5,779
  • 6
  • 37
  • 81

1 Answers1

2

A solution is to add a pseudo element to behave like the other and you will have 6 in total.

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

.grid div {
  flex-basis: 26%;
  height: 50px;
  background-color: red;
  margin-bottom: 20px;
}
.grid:after {
flex-basis: 26%;
  content:"";
}
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Even if you intially have 6 elements, it's not an issue as the pseudo element has no height so it will not create a third row. So whataver the number of elements is in the last row (1,2 or 3) it will always work :

.grid {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  border:1px solid green;
}

.grid div {
  flex-basis: 26%;
  height: 50px;
  background-color: red;
  margin-bottom: 20px;
}
.grid:after {
flex-basis: 26%;
  content:"";
}
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
Temani Afif
  • 211,628
  • 17
  • 234
  • 311
  • @cup_of welcome ;) i added more detail to the answer to show that you can also use it when having 6 elements too – Temani Afif Nov 27 '17 at 22:20