How Do Justify-Content and Align-Items Work in Flexbox?

In CSS Flexbox, justify-content and align-items are the primary container properties used to align elements and distribute unused space. The fundamental distinction between them depends on the flex container's direction: justify-content controls alignment along the main axis, while align-items controls alignment along the perpendicular cross axis. Understanding how these axes operate makes managing element spacing, positioning, and responsive adjustments straightforward.

Understanding Flexbox Axes

Flexbox positions items across two directional axes defined by the flex-direction property:

Because these axes switch depending on flex-direction, justify-content always dictates the primary flow direction, and align-items manages alignment across the secondary direction.

Distributing Space with justify-content

The justify-content property manages how leftover space along the main axis is allocated among and around flex items.

Common Values for justify-content

.flex-container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

Aligning Items with align-items

The align-items property controls how flex items sit and stretch along the cross axis. Unlike justify-content, which primarily distributes spare space across gaps, align-items directly influences item positioning and dimension within the current line.

Common Values for align-items

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

Side-by-Side Comparison

Feature justify-content align-items
Target Axis Main axis Cross axis
Default Value flex-start stretch
Primary Role Distributes remaining space along the primary flow Aligns items and controls stretch across the secondary flow
**Behavior in row** Manages horizontal spacing Manages vertical alignment
**Behavior in column** Manages vertical spacing Manages horizontal alignment

Perfect Centering Example

Combining both properties allows for centering content both vertically and horizontally in just a few declarations:

.center-box {
  display: flex;
  justify-content: center; /* Centers along the main axis */
  align-items: center;     /* Centers along the cross axis */
  height: 100vh;
}

This combination distributes all available main-axis and cross-axis space evenly around the child elements, locking them into the center of the viewport or container.