Flexbox. Playing with flexible boxes.

Raül Martínez
3 min readApr 26, 2018

--

When we want to start distributing the space between different elements of our web page, it is very difficult to be completely exact in the position of them if we play with units that are not relative as “pixels”, “points” … and still with the units such as “%”, “rem”, “vh or vw” is not exact at all either.
Here Flexbox comes into play.

Flexbox is an integrated system in CSS used in the positioning of content within the same container.

Imagine something like that:

Simply a basic structure with 5 divs with the class “child” inside a parent with the class “container”.

How could we structure these children so that instead of vertically they appear horizontally?

If we tested with a display: inline-block in each child and a specific width for each one we could reach something like this:

But what would happen if we need to incorporate a new div into that container?

Everything falls apart because the width of each of the children is fixed and relative to the father.
Let’s try our new friend Flexbox.

To activate Flexbox in an element, we must do it with the display: flex property.

This flex property always works with the children, with which we must activate it in our .container element. And for each child to occupy the maximum within that .container we will put a maximum width. For example, we will use the property for the children, flex-grow: 1. This property is responsible for growing children equally. The result would be …

A correlation of perfectly aligned and distributed elements.

What happens if we want to order them in Vertical? No problem.

We change the height of the .child so they fit better on the screen.

Flexbox is a perfect system to organize elements in an equitable way by different parent elements.

Think of a grid. We will create 3 more .child elements in order to reach 9 elements in total, while in the parent we activate the wrap property that will move the next element that does not fit in the first line to a new line. Such that way.

Una manera muy sencilla de hacer un grid.

A very simple way to make a grid. Easy, right? You can make amazing things with Flexbox, but you have to wait for the next chapter.

--

--