Coded-Aesthetics

CSS3 - Flexbox basics

Flexbox is a two-dimensional layout entity. It provides features like reordering of elements without changing the DOM, easy vertical centering and it let's you specify how elements are to be resized in case there is too much space or not enough space.

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:

flexbox default axis alignment

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:

See the Pen qRJVmQ by Jan Reinsch (@coded-aesthetics) on CodePen.

By putting the property display:flex on the container they align like this:

See the Pen zNmPEa by Jan Reinsch (@coded-aesthetics) on CodePen.

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.

Flex direction

Through the property flex-direction you can change the direction and orientation of the main axis: The default is flex-direction: row. By setting flex-direction:column the alignment of the axes looks like this:

flexbox axis alignment flex-direction column

Other options are flex-direction:row-reverse flexbox axis alignment flex-direction column

and flex-direction:column-reverse flexbox axis alignment flex-direction column

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:

See the Pen XpxVmO by Jan Reinsch (@coded-aesthetics) on CodePen.

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.

See the Pen VPEyae by Jan Reinsch (@coded-aesthetics) on CodePen.

This also works with flipped axes aka flex-direction:column

See the Pen XpxVdG by Jan Reinsch (@coded-aesthetics) on CodePen.

By setting flex-wrap:wrap-reverse the direction of the cross-axis is reversed, so that it points from right to left:

See the Pen ZLqvpV by Jan Reinsch (@coded-aesthetics) on CodePen.

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.

See the Pen NdOXvY by Jan Reinsch (@coded-aesthetics) on CodePen.

The order property is a decimal value like the z-index:

See the Pen vgVppg by Jan Reinsch (@coded-aesthetics) on CodePen.

Flex-items are now ordered according to the value of their order property.