3

Since the initial value of flex-basis is auto, I expected the property to default to auto if omitted in a shorthand notation like this:

flex: 2 1; instead it defaults to 0 !

What's the reason, why it behaves like that?

Michael Benjamin
  • 307,417
  • 93
  • 525
  • 644
kapreski
  • 729
  • 5
  • 19

2 Answers2

3

Because in the flex shorthand property, when flex-grow and, optionally, flex-shrink are declared, and flex-basis is omitted, flex-basis, by definition, defaults to 0.

See:

Michael Benjamin
  • 307,417
  • 93
  • 525
  • 644
  • 2
    I know it is set to `0` the question was why! – kapreski Jul 29 '18 at 16:27
  • 1
    And I specifically answered that question: *Because that is how the values are defined in the spec.* You may as well ask why the `flex-basis` longhand property defaults to `auto`. Why not `0`? Same reason. I even posted the link to the spec definition. – Michael Benjamin Jul 29 '18 at 17:38
0

tl;dr: To make it easy to resize items according to a fixed ratio.

This question only becomes relevant if your flex container has multiple items. In that case, it is a common idiom to set flex: N for some or even all of them. The natural expectation is that the items without this setting keep their size (hence, the default of flex-grow is 0) while the others are sized according to the ratio defined by flex-grow. By natural, I mean that flex; 1, flex: 2, flex: 1 naturally corresponds to the ratio 1:2:1. If flex: N were to default to flex-basis: auto, this expectation could be violated:

 <div style="width:100px;height:100px;display:flex">
    <div style="width:10%;flex:1;border:1px solid black"></div>
    <div style="flex:1;border:1px solid black"></div>
</div>

Instead of both items sharing the space equally, one item is 55px wide and the other 45px.

This begs the question: Why set a width at all (like width: 10%) if you want flex to distribute it anyway? I surmise that this makes it more beginner-friendly and less error-prone.

However, once you've understood how flex-base works, I agree that it can be confusing (that's how I stumbled upon this question...).

Max
  • 117
  • 11