Search code examples
cssflexbox

CSS Flexbox Gap - gap value affecting width calculation


I am using flexbox and the new gap function to add some space between items. I am trying to have 4 items per row so have set item width to be 25% like this...

.container {
  display: flex;
  max-width: 800px;
  width: 100%;
  background: gold;
  flex-wrap: wrap;
  gap: 20px;
}

.item {
  width: 25%;
  background: teal;
}
<div class="container">

  <div class="item">
    Item 1
  </div>
  
  <div class="item">
    Item 2
  </div>
  
  <div class="item">
    Item 3
  </div>
  
  <div class="item">
    Item 4
  </div>
  
  <div class="item">
    Item 5
  </div>
  
  <div class="item">
    Item 6
  </div>
  
</div>

But this is giving me 3 items per row instead, I assume it is because it is taking the gap value into account when calculating widths.

How can I work around this?


Solution

  • You could define the gap in a CSS custom property and then calculate the width of the items with a little bit of math.

    .container {
      --gap: 20px;
      --columns: 4;
      display: flex;
      max-width: 800px;
      width: 100%;
      background: gold;
      flex-wrap: wrap;
      gap: var(--gap);
    }
    
    .item {
      width: calc((100% / var(--columns)) - var(--gap) + (var(--gap) / var(--columns)));
      background: teal;
    }
    <div class="container">
    
      <div class="item">
        Item 1
      </div>
      
      <div class="item">
        Item 2
      </div>
      
      <div class="item">
        Item 3
      </div>
      
      <div class="item">
        Item 4
      </div>
      
      <div class="item">
        Item 5
      </div>
      
      <div class="item">
        Item 6
      </div>
      
    </div>