Center align

Center alignment is one of the most discussed topic in CSS. Flexbox provides a easy and elegant way to solve this layout issue.

The result of center-aligned item inside the container.
The result of center-aligned item inside the container.

Example—Center aligning one item

<div class="container">
  <div class="item">Center aligned.</div>
</div>
.container {
  display: flex;
}
.item {
  margin: auto;
}

The beautify of margin: auto on the child items is that it automatically spread the items across the space with equivalent margins.

Example—Distribute multiple items in container

Multiple items are automatically distributed within container.
Multiple items are automatically distributed within container.

Thanks to the margin: auto, the browser automatically distribute all the items inside the flexbox container equally.

<div class="container">
  <div class="item">Item.</div>
  <div class="item">Item.</div>
  <div class="item">Item.</div>
</div>

Using align-items and justify-content

Alternatively, we can configure the alignment in the container by using the align-items and justify-content properties.

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
.item {
  /* No need to specify the alignment in children */
}

Example—Center aligning multiple items

Multiple items being center aligned.
Multiple items being center aligned.

By using the container’s alignment options, we can center align multiple items together.

html, body {
  height: 100%
}
.container {
  display: flex;
  height: 100%;

  align-items: center;
  justify-content: center;

  flex-direction: column;
}
.box {
  height: 50px;
  width: 300px;
  margin: 0.2em;
}

You can find the live demo in the following link:

http://codepen.io/makzan/pen/dopZxX