CSS flexbox spacing issues with gap property

1.9k Views Asked by At

I am having issues with flexbox. When I use the property gap it is making the columns too wide? I am trying to create a simple 3 column row.

I thought that the gap value would not affect the width set? Ie. flex: 0 1 33.33% and gap 2rem would then adjust the width automatically?

Would anyone have any solutions for this issue?

here is the example - https://codepen.io/CodePlanB1234/pen/WNMypqR

  <div class="row projects--wrapper">
        <div class="card-project--card col-4-12">
          <div class="card-project--image"><img src="/images/bgpic1.jpg" alt="text"></div>

        </div>
        <div class="card-project--card col-4-12">
          <div class="card-project--image"><img src="/images/bgpic1.jpg" alt="text"></div>

        </div>
        <div class="card-project--card col-4-12">
          <div class="card-project--image"><img src="/images/bgpic1.jpg" alt="text"></div>

        </div>
        <div class="card-project--card col-4-12">
          <div class="card-project--image"><img src="/images/bgpic1.jpg" alt="text"></div>

        </div>
        <div class="card-project--card col-4-12">
          <div class="card-project--image"><img src="/images/bgpic1.jpg" alt="text"></div>

        </div>
        <div class="card-project--card col-4-12">
          <div class="card-project--image"><img src="/images/bgpic1.jpg" alt="text"></div>

        </div>
            </div>
1

There are 1 best solutions below

0
On

gap it take space so in my understanding is to use calc function to reset the column wide by using calc function. In these example the flex that have 4 column for each row which is mean it will have 3 gap column in the same row. As for gap you should set as varible so you can change how much the gap it will be given in gap variable.


Here the formula

the formula for width flex item with gap

W = 100%/NC - G/NC*NC-1

NC = number of column on the same row

G = gap range

width = (100% of width row / NC) - (G / NC * NC-1)

.flex {
  display: flex;
  flex-wrap: wrap;
}

.gap {
  --gap: 1em;
  gap: var(--gap);
}

.item-four-col {
  width: calc(100% / 4 - calc(var(--gap)/4*3));
  background-color: red;
}
<div class="flex gap">
  <div class="item-four-col">1</div>
  <div class="item-four-col">2</div>
  <div class="item-four-col">3</div>
  <div class="item-four-col">4</div>
  <div class="item-four-col">5</div>
  <div class="item-four-col">6</div>
</div>