6

I am aiming to have three flex items per row and use space-between so the first and third items in each row touch the outside of the container but remain equally spaced.

This works as intended but the problems arise in the second row when the fifth item doesn't align as I want, directly below the second item. I will have a variable amount of content so need the layout to work with any number of boxes.

I have shown my code below. Can anyone tell me how to fix this?

.main{
    background: #999;
    margin:0 auto;
    width:1300px;
    display:flex;
    flex-wrap: wrap;
    justify-content: space-between;
}


.box{
    background: #7ab9d7;
    color: #555;
    height: 300px;
    width: 30%;
    margin-bottom: 30px;
    text-align: center;
    font-size: 30px;
    padding-top: 120px;
}
<div class="main">
         
          <div class="box">1</div>
          <div class="box">2</div>
          <div class="box">3</div>
          <div class="box">4</div>
          <div class="box">5</div>
         
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Neil K
  • 1,318
  • 1
  • 14
  • 23

1 Answers1

14

Use an invisible pseudo-element that occupies the last slot in the container:

.main::after {
  height: 0;
  width: 30%;
  content: "";
}

The height is 0 so that when rows are filled, and the pseudo-element starts the next line, it doesn't add height to the container.

Full code:

.main {
  background: #999;
  margin: 0 auto;
  width: 500px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.box {
  background: #7ab9d7;
  color: #555;
  height: 30px;
  width: 30%;
  margin-bottom: 30px;
  text-align: center;
  font-size: 30px;
  padding-top: 120px;
}
.main::after {
  height: 0;
  width: 30%;
  content: "";
}
<div class="main">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
  <div class="box">5</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    Great. Works perfectly, thanks! I thought there would be a simple clean flex solution that I was missing but this is a great workaround. – Neil K Jun 23 '16 at 20:10