Centering Things in CSS Using Flexbox


Flexbox makes it easier to design a flexible responsive layout structure without using float or positioning.

Contents

Introduction

I just want to talk about how we would currently layout a page using CSS before flexbox in a browser.

We typically use different positional properties such as position absolute or relative to get elements exactly where we want them on a page or just to tweak them a little bit.

We also use things like floats for creating grid layouts or navigation systems but then we’d be kind of confronted with that problem of collapsing elements and we have to come up with clear fixes.

We’d also probably use things like fixed heights for columns that we want to be equal in height.

Now a lot of the times when we wrote CSS for this it seemed like a lot of work for what it achieves on the page and also it’s sometimes felt a little bit hack in the way we’re doing it.

So this is where CSS flexbox comes in and just blows all of that out of the water. Flexbox is just a new CSS display type that is designed to help us craft those CSS layouts much much easier.

It lets us control the position of elements the size of them, and the spacing of them relative to their parent container elements and each other, and it also works great responsively too.

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

div {
    display: flex;
}

Horizontal Centering

Consider this Markup:

<div class="container">
  <div class="box">
    Box 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;
}
Flexbox horizonal centering
Horizontal Centering

Vertical Centering

justify-content is the X axis and the property name we need for the Y axis is align-items.

Here 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 {
  display: flex;
  align-items: center;
  min-height: 100vh; // height of the browser viewport
}
Vertical Centering
Vertical Centering

Horizontal and Vertical Centering using Flexbox

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;
}
centering vertically and horizontally
Vertically and Horizontally

Conclusion

Flexbox makes a lot of things easier. You can find the code here.


Share on social media

//