Copied to clipboard

Using flexbox

Flexbox is easily one of the most helpful bits of CSS I've ever learned. You can think of it as a tool to help you group divs together side-by-side.

Here are two 25px divs, without flexbox:

In order to apply flexbox, we need to wrap both of those divs in another div. That "container" will be the element we apply flexbox to.

<div class="flex">
    <div class="item"></div>
    <div class="item"></div>
</div>

Then, we can add our CSS:

.flex {
    display:flex;
}

Flex wrapping

If you have too many items and not enough space on the page, it'll either run off of the page, or look very squished, like this:

We can fix this by setting our flex container to wrap. This tells the flex items to wrap onto the next line if there isn't enough space to fit.

Flex alignment

In the above example, our divs have a static width and are further constrained by this page's layout, there's some space left over on the right.

You can use justify-content on your flex container to determine how your flex items are spread out.

For example, here's justify-content:space-between:

and here's justify-content:center:

If you want to space flex items vertically, you can simply add a margin-bottom to them.

Flex order

Changing the flex order can come in handy when you're designing mobile-friendly layouts.

For example, take a look at the demo below. Click the bottom right corner to resize the demo. As the screen space narrows, a @media query kicks in and the layout flexes. Since the sidebar comes first in the HTML, it displays on top and takes up a lot of space on small screens.

With just CSS, you can change the order in which things appear.

.sidebar { 
    order: 2;
}
.content {
    order:1;
}

Try resizing this new version:

Now it flexes to the bottom of the page.

Flex stretching

Sometimes you really need a div to fill the remaining horizontal space. Here is how you do that with flexbox.

The below div has no width set, yet it stretches to fill the entire width.

Our div, (the flex "child"), has the flex-grow:1; property, which tells the item to fill all remaining space.