Flexbox
Flexbox is a way to arrange items into rows or columns. These items will flex based on some rules that you can define.
Flexbox is not just a single CSS property but a whole toolbox of properties that you can use to put things where you need them. Some of these properties belong on the flex container, while some go on the flex items. This is an important concept.
- Flex container: any elements that has
display: flex
on it. - Flex item: any element that lives directly inside of a flex container.
The flex shorthand
The flex
declaration is actually a shorthand for 3 properties that you can set on a flex item. These properties affect how flex items size themselves within their container.
flex
stand for three properties:
flex-grow
flex-shrink
flex-basis
Flex-grow
flex-grow
expects a single number as its value, and that number is used as the flex-item’s “growth factor”.
So the result of flex-grow is the flex item’s size would be growth factor
times bigger.
Flex-shrink
flex-shrink
is similar to flex-grow
, but sets the “shrink factor” of a flex item.
But the flex-shrink
only ends up being applied if the size of all flex items is larger than their parent container.
An important implication to notice here is that when you specify flex-grow or flex-shrink, flex items do not necessarily respect your given values for width. In the above example, all 3 divs are given a width of 250px, but when their parent is big enough, they grow to fill it. Likewise, when the parent is too small, the default behavior is for them to shrink to fit. This is not a bug, but it could be confusing behavior if you aren’t expecting it.
Flex-basis
flex-basis
sets the initial size of a flex item, so any sort of flex-grow
ing or flex-shrink
ing starts from that baseline size.
There is a difference between the default value of
flex-basis
and the way theflex
shorthand defines it if noflex-basis
is given. The actual default value forflex-basis
isauto
, but when you want to only adjust an item’sflex-grow
you can do so directly
What is flex: auto
flex: auto
is one of the shorthands of flex. When auto is defined as a flex keyword it is equivalent to the values of flex: 1 1 auto
.