1

I have a nicely defined grid system:

.col-3-grid {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}
.col-3-grid .grid-item {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 32%;
    -ms-flex: 0 0 32%;
    flex: 0 0 32%;
    max-width: 33.333333%;
}

It looks good when there are 3 elements on a line:

Elements look good when they're 3.

But the moment an uneven number of items that are not first-row 2 or any other rows multiple or 3, this happens:

Elements look bad when they're 5, 8 or so.

Between the 4th and 6th items, there's a gap. This is expected, but this approach is so elegant, I really don't wanna give it up for justify-content: flex-start because then I'd need to add paddings to each of my elements and they'd never align with others.

In short, I wanna keep space-between but make the items go in a line on each row.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
coolpasta
  • 725
  • 5
  • 19

1 Answers1

1

I don't think its possible using justify-content:space-between. However you can use margin to every middle element i.e. 2nd, 5th, 8th, 11th so on...

.col-3-grid .grid-item:nth-child(3n+2) {
  margin: 0 2%;
}

No need to use justify-content:space-between

.col-3-grid {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  flex-wrap: wrap;
}

.col-3-grid .grid-item {
  -webkit-box-flex: 0;
  -webkit-flex: 0 0 32%;
  -ms-flex: 0 0 32%;
  flex: 0 0 32%;
  max-width: 33.333333%;
  height: 30px;
  background: gray;
  margin-bottom: 10px;
}

.col-3-grid .grid-item:nth-child(3n+2) {
  margin: 0 2%;
}
<div class="col-3-grid">
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
</div>
Bhuwan
  • 16,525
  • 5
  • 34
  • 57
  • I know it sounds crazy, but how about I generate an empty box that could just fill the space? Given I know in my back-end code my grid is on 3 columns, perhaps I can just generate an empty box at the end to fill it all? – coolpasta May 24 '18 at 13:07
  • @coolpasta if you can achieve this by just writing a single line css, why write code for the empty box...make no sense to me – Bhuwan May 24 '18 at 13:26