14

In a dom structure like this:

<div id="1">
  <div id="2">
    <div id="3">
    </div>
  </div>
  <div id="4">
    <div id="5">
    </div>
  </div>
</div>

with css specified as:

#1{
  display: flex;
  flex-direction: row;
}
#2, #4{
  flex: 1;
}

The divs with id 2 and 4 will be evenly distributed as long as the sum of the width of the contents in id 3 and 5 does not exceed the width of the dom with id 1.

When the sum exceeds the width, they are not evenly distributed, and one with wider content will take up more width. How can I force 2 and 4 to take up even width using flexbox even in such cases?

I do not want to use width specification by percent. I want to stick to flexbox.

sawa
  • 156,411
  • 36
  • 254
  • 350
  • 1
    First of all, `id` that starts with a number is invalid: http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – Pavlo Jun 08 '13 at 14:43

2 Answers2

20

If you want elements to grow or shrink independently to it's content, specify zero flex basis:

flex-basis: 0;

However, my demo incorrectly works in Chrome: large image stretches it's parent container no matter that zero basis has been set. As a workaround, maximum width can be set:

img {
  max-width: 100%;
  height: auto;
}
Pavlo
  • 35,298
  • 12
  • 72
  • 105
3

To force the equal distribution, you have to add width: 0 to all flex items. This came to my mind after reading Manuel Matuzovic's article, which has a very good in-depth conclusion how flex-grow works.

https://css-tricks.com/flex-grow-is-weird/

  • Not sure why other answers out there don't say this explicitly, but this was the answer on top of everything else that fixed my problem at the end of the day – Emily Chen Oct 21 '20 at 05:49