Search code examples
htmlcssflexboxcss-calc

Adjust 3 box in a row using flexbox


I want to place 3 Box in a row, another 3 in second row. This is working fine if I do not add margin: 2px; and width: calc(33%-4px);. But if I add margin: 2px; and adjust in width as width: calc(33% - 4px); then all are coming in same row. Please let me know what I am doing wrong here with width calc method.

Incorrect Code -

.container { display: flex; flex-wrap: wrap; }
.box { 
  flex-grow: 1; 
  width: calc(33%-4px); 
  height: 100px; 
  background: green;
  margin: 2px;
 }
<div class="container">
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>
  <div class="box">Box 4</div>
  <div class="box">Box 5</div>
  <div class="box">Box 6</div>
</div>

Working Code -

.container { display: flex; flex-wrap: wrap; }
.box { 
  flex-grow: 1; 
  width: 33%; 
  height: 100px; 
  background: green;
 }
<div class="container">
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>
  <div class="box">Box 4</div>
  <div class="box">Box 5</div>
  <div class="box">Box 6</div>
</div>


Solution

  • The margin should match the calc(100% - <this value here>px)
    Also notice that spaces are needed in order for calc(<value>(space)<operator>(space)<value>) to work!

    .container { display: flex; flex-wrap: wrap; }
    .box { 
      flex-grow: 1; 
      width: calc(33% - 2px); 
      margin: 2px;
      height: 100px; 
      background: green;
     }
    <div class="container">
      <div class="box">Box 1</div>
      <div class="box">Box 2</div>
      <div class="box">Box 3</div>
      <div class="box">Box 4</div>
      <div class="box">Box 5</div>
      <div class="box">Box 6</div>
    </div>