On the container: display: flex
or display: inline-flex
flex-direction: row
flex-grow: 0
flex-shrink: 1
flex-basis: auto
width: 100px
. Then it will be used as the flex-basis. If the don't, the content size will be used.flex-wrap: nowrap
Easiest way to make the flex items stretches evenly: flex: 1
. Apply it on each item.
With just those simple declarations, we can create a complex nesting multiple flexbox.
flex
is actually a shorthand for flex-grow
, flex-shrink
, and flex-basis
.
The standard value is flex: 0 1 0%
.
When declared only with 1 value, it's referring to the flex-grow
:
flex: 1
Meaning: grow each child box equally and it is actually flex: 1 1 0%
.
flex-grow
flex: 1
to each flex item div: they will grow equally, to the exact same sizeflex: 2
to 1 item div and flex: 1
to the rest: that box will grow twice wider than each of the rest. flex-shrink
flex-shrink: 0
when you don't want a flex item to shrinkflex-basis
auto
, which mean will acknowledge width declaration of the flex item.flex: 1
means flex: 1 1 0
, meaning we set it to 0, meaning we ignore the declared width. Meaning flex items will be growing or shrinking evenly according to the growth/shrink factor.flex: 1 1 auto
will take declared width into consideration.flex: initial
flex: 0 1 auto
, the initial value.flex: auto
flex: 0 1 auto
.flex: initial
, but can grow too.
flex: none
flex: 0 0 auto
.flex: num+
with num+ is any positive numberflex: num+ num+ 0
.There are 2 axis in the flexbox system: main axis (row) and cross axis (column), and each axis can have 2 directions: regular and reverse.
flex-direction: row
flex-direction: row-reverse
flex-direction: column
flex-direction: column-reverse
height
of a vertical flexboxFor vertical flexbox, pay attention to the height
and flex
declaration. When working with horizontal flexbox, shorthand flex: 1
in items is enough to make a smooth flexbox. This code will collapse empty item box in vertical flexbox because it sets the flex-basis at 0, which means it will ignore the predefined height. If the container doesn't have defined height
either, and all the item boxes are empty, the container will collapse. This doesn't happen in horizontal box, just in vertical box, because a box by standard stretches horizontally to available space, the whole width, while it stretches vertically only onto the extend of content or predefined height.
So, pay attention to:
height
height
flex
shorthand: consider declare flex-basis
separatelyflex-wrap: wrap
By default, items will be shrinking when there's no enough horizontal space in the container. If we want the items size to be respected and goes to the next line, use flex-wrap: wrap
. Below is an example. Shrink and stretch the window horizontally to see the effect.
The default value is flex-wrap: nowrap
btw, in which items will be shrinking instead. The problem is, overflow can happen if items are not able to shrink or can't shrink small enough to fit.