FlexBox - Part 1 - Better Control Over Layout

What is FlexBox

FlexBox is a one dimensional CSS layout, consisting of a container and one or more children. Its power lies in being able to determine the order and direction of its children, being able to position them horizontally and vertically, and being able to grow and shrink the children to fill the available space.

Flexbox is powerful, and simplifies lots of the layout problems we have historically have had to deal with. Whilst FlexBox itself can be a little difficult to grasp to start with, it doesn't take long to learn and soon be wondering how you coped without it.

Examples of Problems that FlexBox Solves

Grid Systems

Historically most grid systems used float or inline-block, neither of which worked perfectly as a grid system.

Floats are difficult to work with, and they were really only intended to be used to wrap text around an element. But they presented a way to change the sequential nature of HTML, by being able to line elements up horizontally. But floated layouts are generally considered to be fragile, suffer from problems such as pushdown, and needed clearfix hacks in order to work well for layout.

inline-block whist being great for being able to line up elements in a horizontal direction, it suffers from white space issues, which forces you to write your HTML is written in a certain way, else you would get extra spaces in your layout. Also any element being unexpectedly too large will cause the whole layout to wrap.

They both also suffer when it comes to responsive design, being unable to reorder elements to better suit the form factor.

FlexBox was designed to fix the problems of floats and inline-block layouts, and give you even more possibilities then you had before.

Vertical Center

Vertical center has always been difficult, particularly if the dimensions of the element are unknown. You were always forced to use hacky methods, such as negative margins, tables, full height pseudo elements, or zeroed top and bottom properties.

With FlexBox you can align items easily with the align-items, align-self, and justify-content properties.

Full Height Columns

In layout it is very common to use the "Holy grail Layout", that is a layout where you have a header, a footer (that must never be positioned higher than the height of the window), and typically three columns which must fill the vertical space, and all columns need be as tall as the tallest of them.

The image above shows the issues presented when using the float solution for this. Due to the height of block elements being determined by their content, the columns will fail to adjust to the size of its siblings. And the cleared footer element will only be positioned directly under the largest of the floats, leaving a gap at the bottom.

Flexbox solves these problems by allowing the children of a flex container fill the available space.

Fluid Space Allocation