We're live-coding on Twitch! Join us!

Centering Things with CSS Flexbox

Code

Flexbox has been out for a while now in CSS. Looking at the Can I Use Flexbox page, we can see that it's acceptable in all modern browsers and even a little in IE!

Centering things in CSS before flexbox was always a chore. None of the major methods ever worked 100% consistently. Flexbox makes centering items as simple as 3 lines!

To set an item to use flexbox, we just have to use the CSS display property:

div {
    display: flex;
}

While flexbox may seem easy to use with the above line, it can be very powerful if you understand all of its properties. Let's see some common flexbox centering tasks and how we can achieve them.

Centering Horizontally with Flexbox

Centering things in flexbox is very powerful. Let's talk about how to center horizontally. Remember that the styles have to go on the parent element.

<div class="container">
  <div class="box">
    i am centered horizontally!
  </div>
</div>

To get the box to center horizontally, we need to set the parent container to display: flex;. Then we can use justify-content to center horizontally!

.container {
    display: flex;
    justify-content: center;
}

By default, justify-content refers to the X axis (horizontal). We set this to center to get our child elements to center horizontally with flexbox.

Here's the CodePen:

Centering Vertically

Centering vertically is similar to to centering horizontally except for the property name. justify-content is the X axis and the property name we need for the Y axis is align-items.

<div class="container">
  <div class="box">
    i am centered vertically!
  </div>
</div>

In the CSS, we'll use align-items: We also have to remember to set a height otherwise the div won't be able to center itself.

.container {
  min-height: 100vh; // height of the browser viewport
  display: flex;
  align-items: center;
}

Here's the CodePen:

Centering Horizontally and Vertically with Flexbox

To center horizontally and vertically, we will use both justify-content and align-items.

.container {
  min-height: 100vh; // height of the browser viewport
  display: flex;
    justify-content: center;
  align-items: center;
}

Here's the CodePen:

Spacing to the Left and Right

While this one isn't about centering, it's more about spacing things left and right so that there is a gap in the center. This is a useful trick for navigation bars.

.container {
    display: flex;
    justify-content: space-between;
}

Here's the CodePen:

Conclusion

Flexbox makes a lot of things easier to do in CSS. Centering is something I use every day in CSS. Thank you flexbox!

Like this article? Follow @chrisoncode on Twitter