11

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?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

3 Answers3

12

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>
chazsolo
  • 7,873
  • 1
  • 20
  • 44
7

You can subtract the gap from the width. 20px gap * 3 / 4 (columns)

.item {
   width: calc(25% - 15px);
   background: teal;
}
Moshe Sommers
  • 1,466
  • 7
  • 11
3

Consider this other approach, it's easier. Just enter the gap value and that's it.

.container {
  display: grid;
  grid-template-columns: auto auto auto auto;
  max-width:800px;
  background-color:gold;
  gap:20px;
}

/* -- Select all <div> elements within the container -- */
.container > div {
  background-color: teal;
}
<div class="container">

  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
  <div>Item 4</div>
  <div>Item 5</div>
  <div>Item 6</div>

</div>
Gass
  • 7,536
  • 3
  • 37
  • 41