2

In my code below, when I add padding it should add to width since I am using border-box. But it is not working why? Can anyone help me.

If I add some margin or padding my child__wrapper is pushed into new line why?

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.wrapper {
  display: flex;
  flex-wrap: wrap;
  margin: 0;
  padding: 0;
  width: 100%;
}

.child__wrapper {
  height: 300px;
  flex: 0 0 33.3%;
  margin: 10px;
  box-sizing: border-box;
  background: rebeccapurple;
}
<div class="wrapper">
  <div class="child__wrapper">1</div>
  <div class="child__wrapper">2</div>
  <div class="child__wrapper">3</div>
  <div class="child__wrapper">4</div>
  <div class="child__wrapper">5</div>
  <div class="child__wrapper">6</div>
  <div class="child__wrapper">7</div>
  <div class="child__wrapper">8</div>
  <div class="child__wrapper">9</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60

1 Answers1

7

Keep in mind that box-sizing: border-box brings padding and borders into the width / height calculation, but not margins. Margins are always calculated separately.

The box-sizing property takes two values:

  • content-box
  • border-box

It does not offer padding-box or margin-box.

Consider those terms when referring to the CSS Box Model.

enter image description here

source: W3C

So when you set your item widths to 33.3% and add 10px margins on the right and left, an overflow condition is triggered, resulting in a wrap of the third item.

33.3% + 33.3% + 33.3% + 10px + 10px + 10px + 10px + 10px + 10px > 100%

Instead, try this on the items:

flex: 1 0 26%

This shorthand rule breaks down to this:

  • flex-grow: 1
  • flex-shrink: 0
  • flex-basis: 26%

With flex-grow: 1 there's no need for flex-basis to be 33.3%.

Since flex-grow will consume free space in the row, flex-basis only needs to be large enough to enforce a wrap.

In this case, with flex-basis: 26%, a maximum of three items can exist on the line, there's plenty of space left for margins, and flex-grow fills any gaps.

.wrapper {
  display: flex;
  flex-wrap: wrap;
}

.child__wrapper {
  flex: 1 0 26%;
  margin: 10px;
  height: 300px;
  box-sizing: border-box;
  background: rebeccapurple;
}

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
<div class="wrapper">
  <div class="child__wrapper">1</div>
  <div class="child__wrapper">2</div>
  <div class="child__wrapper">3</div>
  <div class="child__wrapper">4</div>
  <div class="child__wrapper">5</div>
  <div class="child__wrapper">6</div>
  <div class="child__wrapper">7</div>
  <div class="child__wrapper">8</div>
  <div class="child__wrapper">9</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701