Flex Shorthand Notation
In this lesson, we will look at how the flex CSS property gives us a compact way to control the flex-grow, flex-shrink, and flex-basis values in one rule.
We'll cover the following
Flex
The flex
property is a shorthand notation for specifying the flex-grow
, flex-shrink
, and flex-basis
properties in one rule.
The format of flex
looks as follows:
.flex-item {
flex: <flex-grow> <flex-shrink> <flex-basis>;
}
Example:
.flex-item {
flex: 2 3 400px;
}
The above example is equivalent with the following properties:
.flex-item {
flex-grow: 2;
flex-shrink: 3;
flex-basis: 400px;
}
It is important to note that similar to flex-grow
, flex-shrink
, and flex-basis
, flex
is also applied on individual flex-items.
The flex
property can take one, two, or three values. We have already examined the version with three values. We will now get to know flex
rules with one or two property values.
One value after flex
When only one value is present, most of the time, we influence flex-grow
only.
In precise terms, whenever the only flex
property value is one number, then we only specify the flex-grow
rate with default flex-shrink
and flex-basis
. The default value of flex-shrink
is 1
, while the default value of flex-basis
is 0
:
.flex-item {
flex: 2;
}
is equivalent to:
.flex-item {
flex: 2 1 0;
}
There are a few other flex
values that are worth noting:
flex: auto;
is fully flexible with aflex-grow
andflex-shrink
ratio of 1. It also takes theflex-basis: auto;
value that sets the basis according to the width and the height of the component.flex: initial;
is equivalent toflex: 0 1 auto;
. The difference betweeninitial
andauto
is thatflex: initial
does not grow with the container. It only shrinks to fit in the container.flex: none;
is fully inflexible. This implies aflex-grow
andflex-shrink
of0
, while theflex-basis
isauto
.
For example: Suppose we have a Flex-container with variable width, and three flex-items with a base width of 150px
. Let’s see how the elements with different flex
properties react.
Get hands-on with 1400+ tech skills courses.