Centering Things with CSS Flexbox

Centering Things with CSS Flexbox

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!

Flexbox Browser Compatibility

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:

css
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 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.

html
<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!

css
.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.

justify-content: center

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.

html
<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.

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

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

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

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.

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

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

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

In this article...

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)