Reputation: 6822
The Mozilla Developer Network flex
article says of its syntax:
One-value syntax: the value must be one of:
- a unitless
<number>
: then it is interpreted as<flex-grow>
.- a valid value for width: then it is interpreted as
<flex-basis>
.- one of the keyword values
none
,auto
, orinitial
.
The second bullet implies that flex: 20%;
is equivalent to flex-basis: 20%;
, as 20%
is a valid value for width
.
However, that is not the case in practice:
.container {
display: flex;
}
.container>div {
padding: 6px;
}
.one {
background: #fcc9e5;
flex: 20%;
}
.two {
background: #ecaef9;
flex: 1;
}
<div class="container">
<div class="one">one</div>
<div class="two">two</div>
</div>
.container {
display: flex;
}
.container>div {
padding: 6px;
}
.one {
background: #fcc9e5;
flex-basis: 20%;
}
.two {
background: #ecaef9;
flex: 1;
}
<div class="container">
<div class="one">one</div>
<div class="two">two</div>
</div>
So, what is happening here?
Upvotes: 3
Views: 639
Reputation: 371699
How does the flex shorthand handle a single value that is represented as a percentage?
Very simple. Like this:
flex: 20%
Is equivalent to:
flex-grow: 1
flex-shrink: 1
flex-basis: 20%
The people at MDN have apparently misinterpreted the flex
definition in the spec, which is actually a bit confusing.
On the one hand, the spec says the Initial Value for flex
is flex: 0 1 auto
.
But if you read the text right below, it says (as pointed out by @BoltClock in his answer), that the value for flex-grow
is 1
when omitted.
So, bottom line, in your first example, flex: 20%
is equivalent to:
flex-grow: 1
flex-shrink: 1
flex-basis: 20%
While in your second example, flex-basis: 20%
is equivalent to:
flex-grow: 0
(the initial value)flex-shrink: 1
(the initial value)flex-basis: 20%
By the way, this is exactly why the flexbox specification makes this recommendation:
Authors are encouraged to control flexibility using the
flex
shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.
Upvotes: 1
Reputation: 724192
The spec says that, in a flex
shorthand declaration, when <flex-grow>
and <flex-shrink>
are omitted, they both default to 1. (MDN incorrectly states that <flex-grow>
defaults to 0.)
This means that the shorthand declaration flex: 20%
is equivalent to flex: 1 1 20%
.
Specifying only flex-basis: 20%
leaves flex-grow
and flex-shrink
at their initial values of 0 and 1 respectively, making that longhand declaration by itself equivalent to the shorthand flex: 0 1 20%
.
Upvotes: 6