Reputation: 771
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?
Upvotes: 3
Views: 1044
Reputation: 371719
When omitted in the shorthand notation, flex-basis
does not always default to 0
. For example:
In flex : initial
(0 1 auto
), the flex-basis
component has a value of auto
.
In flex: none
(0 0 auto
), the flex-basis
component has a value of auto
.
In flex: auto
(1 1 auto
), the flex-basis
component has a value of auto
.
So why does flex-basis
have a value of 0
when preceded by two flex factors? The spec doesn't explain. It just says, "When omitted from the flex
shorthand, its specified value is 0
."
My best guess at this time would be this: Considering that the other three flex
values resolve to flex-basis: auto
, perhaps spec authors wanted to provide developers with one option where the value defaulted to 0
.
More:
Upvotes: 4
Reputation: 156
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...).
Upvotes: 2