Centering and aligning with Flexbox

on
  • CSS

Centering content in CSS was always quite annoying and sometimes really painful. From abusing the line-height property to hacking with display: table-cell and even using absolute positioning with negative margins, every approach had its downsides and maintainability hell. Luckily with the new CSS3 Flexible Layout Standard, centering and aligning objects is easy as pie.

For all the examples showed below, I'm going to use these basic CSS definitions, everything else will be inline-styles:

  .example-container { border: 1px solid black; height: 150px }
  .example-child { background: red; width: 50px; height: 50px; margin: 5px }

With Flexbox, it is really easy to center a child element, without even touching the childs styling. By just setting the display property to flex and using align-items, which aligns the containers content vertically, and justify-content, which aligns the content horizontally, to center we easily centered the child in our container.

<div class="example-container"
     style="display: flex; align-items: center; justify-content: center">
  <div class="example-child"></div>
</div>

It is also possible to horizontally align the child itself in the container.

<div class="example-container"
     style="display: flex; justify-content: center">
  <div class="example-child" style="align-self: center"></div>
</div>

This of course can be mixed, assuming we center by default on the container, we are able to align other items on top or bottom. By setting the childs align-self to either flex-start and flex-end we align them on top / bottom, the values are called start and end because the Flexible Box Layout has the ability to change the order of items in a flex container.

<div class="example-container"
     style="display: flex; align-items: center; justify-content: center">
  <div class="example-child" style="align-self: flex-start"></div>
  <div class="example-child"></div>
  <div class="example-child" style="align-self: flex-end"></div>
</div>

More in depth documentation about Flexbox can be found on the Mozilla Developer Network - Using CSS flexible boxes. If you encounter browser incompatibilities there is a nice Github repository which covers a lot of Flexbox bugs: https://github.com/philipwalton/flexbugs

Happy aligning! :)