Ronalds Vilciņš

Centering flexbox items

Flexbox makes the common “centre this in both directions” problem pleasantly small. Put the layout rules on the parent:

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

justify-content centres the items along the main axis. With the default flex-direction: row, that means horizontally. align-items centres them along the cross axis, which is vertical in this case.

That axis detail matters. If you change the container to flex-direction: column, the directions swap even though the property names stay the same.

If you only need horizontal centring, keep justify-content: center. If you only need vertical centring, keep align-items: center. And remember that both properties belong on the flex container, not the child you are trying to centre.

Enjoyed reading this?

If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.

← Back to all articles