4

I have a flexbox with two children. I want both children to have equal size, despite that one has padding and the other doesn't.

Here's a demo. I want the blue and green boxes to be equal in size:

html, body, .container {
  margin: 0;
  width: 100%;
  height: 100%;
}

.container {
  display: flex;
}

.container div {
  flex: 1;
  min-width: 0;
  flex-basis: 0;
}

.first {
  background: cornflowerblue;
}

.second {
  background: lightgreen;
  padding: 100px;
}
<div class="container">
  <div class="first"> </div>
  <div class="second"> </div>
</div>

I know that I could use width: 50%, but that's not direction-agnostic and breaks if I add more elements.

Omar Einea
  • 2,478
  • 7
  • 23
  • 35
BonsaiOak
  • 27,741
  • 7
  • 30
  • 54
  • Might be useful: https://stackoverflow.com/questions/37785345/how-to-get-flexbox-to-include-padding-in-calculations – sol Mar 04 '18 at 22:08
  • When you say `flex: 1`, that is equivalent to `flex-grow: 1`, `flex-shrink: 1` and `flex-basis: 0`. So adding `flex-basis: 0` later in the code is redundant. – Michael Benjamin Mar 04 '18 at 22:18

1 Answers1

4

You need both the divs to be the 50% (flex:1) and then have another div inside the second one that has the padding. That way both the parents have the same width and the second one has the padding within it.

html, body, .container {
  margin: 0;
  width: 100%;
  height: 100%;
}

.container {
  display: flex;
}

.container > div {
  flex: 1;
}

.first {
  background: cornflowerblue;
}

.second {
  background: lightgreen;
}

.second > div {
  padding: 100px;
}
<div class="container">
  <div class="first">first</div>
  <div class="second">
      <div>second</div>
   </div>
</div>
gavgrif
  • 15,194
  • 2
  • 25
  • 27