8

I want to make a half-half layout. So I made a <div> that had display: flex; and put two children that had flex-grow: 1;. It looked like what I expected, a half-half layout. But when I put something in one of the children, it got larger than the other.

I can’t quite grasp why it works this way. http://codepen.io/anon/pen/rOvpPM

Could you please tell me the why and the proper CSS for it?

3 Answers3

10

Flexbox works that way. If you have two elements (or any amount of elements) in a flex-box, and give them all the same flex-grow, they will all 'grow' the same amount.

If you have a parent flex container with a width of 300px, with two children; one with a width of 0px, and another with 100px, both will grow an additional 100px, resulting in a 100px and a 200px div.

If you want them both to be 50% of the width, just add

width: 50%;

and remove

flex-grow: 1;

from the CSS.

Hope this helps

Gust van de Wal
  • 5,211
  • 1
  • 24
  • 48
7

As already mentioned by Gust, the initial width is also important. If you haven't specified it, it's calculated by the content. This is the so called flex-basis.

So you need to define the flex-basis, for example:

.half {
  flex-basis: 100px;
  flex-grow: 1;
}

If you just use the shorthand property

.half {
  flex: 1;
}

it will also set the flex-basis to 0, so the space get's seperated evenly. A good source for more information is css-tricks.com.

hawc
  • 328
  • 2
  • 14
1

A pure flexbox Solution is just:

flex: 1

The Problem

flex: 1 is a shorthand to set flex-grow to 1, BUT they are not the same.

flex: 1 means:

flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;// !!!

When using flex-grow: 1

flex-grow: 1;
flex-shrink: 1;
flex-basis: auto;// oops !!!

flex-basis: auto - If an item has a width set the size will be based on that width. In your case by writing to your <span> you are actually expanding your first <div class="half">

flex-basis 0 - The item size is not taken into consideration for the space-sharing calculation. In your case the first and second <div> will have equal width regardless of their actual size.

To see the difference set your width to an absolute (fixed) value:

.flexContatiner
{
  width: 500px;
}

Best documentation on these topics can be found here:

Controlling ratios of flex items along the main axis

To see more detailed answers from other Devs on flex-1 and flex-grow see below links:

The difference between flex:1 and flex-grow:1

To me this one was the best explained/illustrated!

Make flex-grow expand items based on their original size