Flexbox

Flexbox is a layout model that allows you to easily create a responsive page. You use Flexbox by setting a container to be flex-container.

Setting an element as a flex container is as simple as setting the the display property to flex. This is usually done like this:

display: flex;

If you want to set an inline element as a flex container, you would do it like this:

display: inline-flex;

 

Once a container is setup as a flex container, its children become flex items. This means that the power of flexbox is at your disposal.

Where you needed to use various CSS tricks previously to horizontally and vertically center items responsively, Flexbox makes this very simple:

Align items vertically:

align-items: center;

Align items horizontally with:

justify-content: center;

 

One of the side-effects of flexbox, is that it puts items side-by-side on the same horizontal row. You can change this so that items are stacked vertically with:

flex-direction: column;

 

Elements can be both Flexbox containers and Flexbox items, and often you'll find yourself turning flex containers into flex items in order to use the power of Flexbox on them too.

A couple of useful tips I found when using Flexbox:

Setting a margin to auto will ensure that there is the maximum space between items:

For example, using the following will ensure that there is the largest possible space between the element with the property, and the next element on the same line.

margin-right: auto;

You can also set the flex property to 1 to have an element occupy all remaining space.

If you find that you need to override the container's alignment settings for a specific element, you can do it with the align-self property.

I also found it useful to temporarily give a container a bright background color while styling it. This allows you to easily see exactly what effects various changes have on your container, and makes troubleshooting much easier.

An important note to remember with Flexbox when compared to other options such as CSS Grid, is that Flexbox is for one-dimensional layouts.