CSS Flexible Box Layout (Flexbox) Dynamic Vertical and Horizontal Centering (align-items, justify-content)


Example

Simple Example (centering a single element)

HTML

<div class="aligner">
  <div class="aligner-item">…</div>
</div>

CSS

.aligner {
  display: flex; 
  align-items: center;
  justify-content: center;
}

.aligner-item {
  max-width: 50%; /*for demo. Use actual width instead.*/
}

Here is a demo.


Reasoning

PropertyValueDescription
align-itemscenterThis centers the elements along the axis other than the one specified by flex-direction, i.e., vertical centering for a horizontal flexbox and horizontal centering for a vertical flexbox.
justify-contentcenterThis centers the elements along the axis specified by flex-direction. I.e., for a horizontal (flex-direction: row) flexbox, this centers horizontally, and for a vertical flexbox (flex-direction: column) flexbox, this centers vertically)

Individual Property Examples

All of the below styles are applied onto this simple layout:

<div id="container">
  <div></div>
  <div></div>
  <div></div>
</div>

where #container is the flex-box.

Example: justify-content: center on a horizontal flexbox

CSS:

div#container {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

Outcome:

horizontal centering

Here is a demo.

Example: justify-content: center on a vertical flexbox

CSS:

div#container {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

Outcome:

vertical centering

Here is a demo.

Example: align-content: center on a horizontal flexbox

CSS:

div#container {
  display: flex;
  flex-direction: row;
  align-items: center;
}

Outcome:

horizontal centering with align-center

Here is a demo.

Example: align-content: center on a vertical flexbox

CSS:

div#container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

Outcome:

vertical centering with align-center

Here is a demo.

Example: Combination for centering both on horizontal flexbox

div#container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

Outcome:

horizontal centering both combination

Here is a demo.

Example: Combination for centering both on vertical flexbox

div#container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

Outcome:

horizontal centering both combination

Here is a demo.