2

I have a simple grid using flex. Works fine but my issue is when there's 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.

Here's 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, there's 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 there's a better flexy way to do it.

halfer
  • 19,824
  • 17
  • 99
  • 186
cup_of
  • 6,397
  • 9
  • 47
  • 94

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
  • 245,468
  • 26
  • 309
  • 415
  • @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