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.

2
  • Might be useful: stackoverflow.com/questions/37785345/…
    – sol
    Commented Mar 4, 2018 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. Commented Mar 4, 2018 at 22:18

1 Answer 1

6

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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.