Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing justify-content: space-between on last row [duplicate]

Tags:

html

css

flexbox

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>
like image 290
Neil K Avatar asked Jun 23 '16 19:06

Neil K


1 Answers

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>
like image 83
Michael Benjamin Avatar answered Nov 07 '22 00:11

Michael Benjamin