karim karim - 6 months ago 14
HTML Question

flexbox margin cause overflow

i have a little problem of overflowing with flexbox :

html

<div class="first">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>


css

* {
box-sizing: border-box;
}

body {
margin: 50px;
}
.first {
display: flex;
flex-flow: row nowrap;
}

.child {
background: red;
border: 1px blue solid;
height: 10px;
flex: 0 0 33.3%;

margin-right: 10px;
}

.first :last-child {
flex: 0 0 33.4%;
}


the problem is that the last child is overflowing, why?? i used box-sizing to border-box?

Answer

How to add margin between children without causing the overflow

I think this is what you are trying to do:

* {
  box-sizing: border-box;
}

body {
  margin: 50px;
}

.first {
  display: flex;
  flex-flow: row nowrap;
  border:1px solid green;
}

.child {
  background: red;
  border: 1px blue solid;
  height: 10px;
  flex: 1; /* equal widths */
  margin-right: 10px;
}
.first :last-child {
  margin-right: 0;
}
<div class="first">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

Alternatively, you can use calc to set the child widths and justify-content:space-between on the flex-container

* {
  box-sizing: border-box;
}
body {
  margin: 50px;
}
.first {
  display: flex;
  flex-flow: row nowrap;
  border: 1px solid green;
  justify-content: space-between;
}
.child {
  background: red;
  border: 1px blue solid;
  height: 10px;
  width: calc((100% - 20px)/3);
  /* or */
  flex: 0 0 calc((100% - 20px)/3);
}
<div class="first">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>