0

I would like to set 3 items per row. I tried something like that but, now I have 2 items per row because of margin and border. How should i implement this to have always 3 items per row

.App {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.parent {
  width: 600px;
  display: flex;
  flex-wrap: wrap;
}

.item {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #000;
  margin: 5px;
  width: 33%;
}
    <div className="App">
      <div className="parent">
        <div className="item">1</div>
        <div className="item">2</div>
        <div className="item">3</div>
        <div className="item">4</div>
        <div className="item">5</div>
        <div className="item">6</div>
        <div className="item">7</div>
        <div className="item">8</div>
        <div className="item">9</div>
        <div className="item">10</div>
      </div>
    </div>
  );
Kameron
  • 10,240
  • 4
  • 13
  • 26
INeedYourHelp
  • 131
  • 1
  • 2
  • 8

3 Answers3

0

You can use width: calc(100%/3 - 12px); on .item.

The 100%/3 will do 3 in a row. Then the -12px accounts for margin: 5px both sides = 10px. Then the same with border. 1px on either side affecting the width gives you 2px. For a total of 12px.

Note: you can use box-sizing: border-box; on .item to avoid having to use the 1px on either side of the border in the calculation.

.App {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

.parent {
  width: 600px;
  display: flex;
  flex-wrap: wrap;
}

.item {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #000;
  margin: 5px;
  width: calc(100%/3 - 12px);
  /*box-sizing: border-box; - would make the calc -10px instead of -12px*/
}
<div class="App">
  <div class="parent">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
    <div class="item">10</div>
  </div>
</div>
Kameron
  • 10,240
  • 4
  • 13
  • 26
0

You can try setting flex-basis:33% on the item element instead of width

.item {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #000;
  margin: 5px;
  flex-basis: 33%;
}
-2

You have to keep in mind that a margin and border expands the size of the div. In your scenario, you have set the div to be 33%, which means the 3 divs in total occupy 99% of the parents width. The remaining 1% is not enough for all the margins and borders.

What I suggest is put the div size to around 30% , or use padding instead of margin .

KGusta
  • 11
  • 1