user10844537
user10844537

Reputation:

What does units on first value accomplish when using "flex" shorthand?

Documentation about the flex shorthand on MDN say:

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, or initial.

Two-value syntax: the first value must be a unitless and it is interpreted as . The second value must be one of:

a unitless <number>: then it is interpreted as <flex-shrink>.
a valid value for width: then it is interpreted as <flex-basis>.

Three-value syntax:

the first value must be a unitless <number> and it is interpreted as <flex-grow>.
the second value must be a unitless <number> and it is interpreted as <flex-shrink>.
the third value must be a valid value for width and is interpreted as <flex-basis>.

But I've seen in many places this shorthand being used like:

flex: 30% 0 0;

I can see and edit this values on the web inspector, and see that they render different values in the browser; but not entirly clear exactly what effect does it have.

Since it's a three value syntax, the first value should be interpreted as flex-grow, but that property expects a unitless number.

How is a percentage applied in a case like this? And is this defined somewhere?

Upvotes: 1

Views: 53

Answers (1)

BoltClock
BoltClock

Reputation: 724202

The shorthand

flex: 30% 0 0;

is equivalent to

flex: 0 0 30%;

where the first 0 is <flex-grow>, the second 0 is <flex-shrink>, and the 30% is <flex-basis>. As long as each of the three component values corresponds 1:1 to a unique longhand property, it doesn't matter what order values with different units appear in. Of course, given two unitless values, the first always corresponds to <flex-grow> and the second to <flex-shrink>.

This is documented in the grammar of the flex shorthand:

none | [ <‘flex-grow’> <‘flex-shrink’>? || <‘flex-basis’> ]

The || "separates two or more options: one or more of them must occur, in any order", as documented in css-values-3.

Upvotes: 5

Related Questions