2

Hello! Can you help me? I'm trying to do two column layout with same spacing between items in same column. Two columns layout

.flex {
  margin: 0;
  padding-left: 0;
  list-style: none;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  align-content: center;
}

.item {
  width: 45%;
  height: 200px;
  margin-bottom: 10px;
  background-color: navy;
}

.item:nth-child(1) {
  height: 210px;
}

.item:nth-child(2) {
  height: 500px;
}

.item:nth-child(3) {
  height: 360px;
}

.item:nth-child(4) {
  height: 400px;
}

.item:nth-child(5) {
  height: 150px;
}
<div class="flex">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Thanks for every good advice & your help!

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
trip1e
  • 47
  • 1
  • 7

1 Answers1

3

You could use column-count instead of flexbox. In this situation, there's no need to implement a flexible box layout. You're not trying to maintain identical sizes or adjust for any odd alignment.

.flex
{
  margin: 0;
  padding-left: 0;
  list-style: none;
  column-count: 2;
  column-gap: 10px;
}

.item{
  height: 200px;
  margin-bottom: 10px;
  background-color: navy;
  break-inside: avoid;
}

.item:nth-child(1){height: 210px;}
.item:nth-child(2){height: 500px;}
.item:nth-child(3){height: 360px;}
.item:nth-child(4){height: 400px;}
.item:nth-child(5){height: 150px;}
<div class="flex">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Here's a way to use percentages for the column gap. It uses 0px column-gap and a negative margin on the container to adjust for the excess margins on the left and right.

.flex
{
  margin: 0;
  padding-left: 0;
  list-style: none;
  column-count: 2;
  column-gap: 0;
  margin: 0 -1.25%;
}

.item{
  height: 200px;
  margin-bottom: 10px;
  background-color: navy;
  break-inside: avoid;
  margin: 0 2.5% 5%;
}

.item:nth-child(1){height: 210px;}
.item:nth-child(2){height: 500px;}
.item:nth-child(3){height: 360px;}
.item:nth-child(4){height: 400px;}
.item:nth-child(5){height: 150px;}
<div class="flex">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129