Main Axis vs Cross Axis Alignment

Flexbox Has Two Axes, Not One

Every flex container has a main axis (the direction items flow, set by flex-direction) and a cross axis, which runs perpendicular to it. Which properties control which axis depends entirely on this direction.

flex-directionMain axisCross axis
row (default)HorizontalVertical
columnVerticalHorizontal

justify-content: Aligns the Main Axis

.row {
  display: flex;
  justify-content: center; /* centers items horizontally, in row mode */
}

Other common values include flex-start, flex-end, space-between and space-around, all describing how leftover space is distributed along the main axis.

align-items: Aligns the Cross Axis

.row {
  display: flex;
  align-items: center; /* centers items vertically, in row mode */
}

The Classic Centering Combination

.center-everything {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

This two-line combination is one of the most common patterns in modern CSS for centering content both horizontally and vertically, replacing much clunkier centering techniques from before Flexbox existed.

align-self: Overriding One Item

.item-special {
  align-self: flex-end; /* just this one item ignores align-items */
}

align-self lets a single flex item opt out of the container's align-items value along the cross axis, without affecting its siblings.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.