CSS3 - Flexbox basics
What is a flexbox?
A flexbox is a two-dimensional layout entity. This means elements inside a flexbox, which are called flex-items, will be aligned after two axes: The main-axis and the cross-axis. By default they are aligned like this:
How to make an element a Flexbox
Usually, when you have a list of divs, they will be vertically stacked on top of each other inside their container like so:
By putting the property
display:flex on the container they align like this:
The flex-items are now aligned along the main-axis, which points from left to right by default. Note that the flex-items don’t take up the whole space of the flexbox along the main-axis.
Through the property
flex-direction you can change the direction and orientation of the main axis: The default is
flex-direction:column the alignment of the axes looks like this:
Other options are
which flip the direction of the respective main-axis.
Flex-wrap or welcome to 2D
In the previous paragraphs, flex-items were not aligned two-dimensionally yet. This is because the flex-items did not take up the whole space of the main-axis. So we give each flex-item a width of 100px so they exceed the space of the main axis:
But as you can see, the items don’t wrap into the next row. To make this happen you need to set
flex-wrap:wrap on the container.
This also works with flipped axes aka
flex-wrap:wrap-reverse the direction of the cross-axis is reversed, so that it points from right to left:
Reordering of flex-items through flex order
The order of flex-items can be changed by assigning the order property to individual flex-items. By default the order property is 0.
The order property is a decimal value like the z-index:
Flex-items are now ordered according to the value of their order property.