Nesh
Nesh

Reputation: 2561

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>

Upvotes: 2

Views: 1775

Answers (2)

Avyn E.
Avyn E.

Reputation: 46

Change

width: calc(30%-4px)

to

width: calc(30% - 4px);

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

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>

Upvotes: 1

Related Questions