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?
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?
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:
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...).