Flex Alignment

Stop guessing how to center a div. Learn how Flexbox distributes space along the main and cross axes.

CSS6 min readConcept 20 of 43

What it is

Flexbox alignment properties dictate how extra space is distributed inside the parent container.

justify-content aligns items along the **Main Axis**. align-items aligns items along the **Cross Axis**.

Why it matters

Perfectly centering an element vertically used to be the hardest thing in CSS, often requiring negative margins, absolute positioning, or table-cell hacks. Flexbox alignment solved this entirely. Mastering these properties gives you absolute control over spacing.

How it works

1. **Main Axis vs Cross Axis**: If flex-direction: row (the default), the Main Axis is horizontal (left to right) and the Cross Axis is vertical (top to bottom). If flex-direction: column, they swap!

2. **justify-content**: Controls alignment on the Main Axis. Common values: flex-start, center, flex-end, space-between (pushes items to the edges), and space-evenly (equal gaps everywhere).

3. **align-items**: Controls alignment on the Cross Axis. Common values: stretch (default), flex-start (top), center, and flex-end (bottom).

Try it

Toggle the flex-direction to observe the Axis Swap in real-time. Then, experiment with justify-content and align-items to see how they control the items along the active axes.

The Alignment Axis Swap

Flex Direction

Determines the Main Axis.

justify-content

Controls the MAIN AXIS (Horizontal).

align-items

Controls the CROSS AXIS (Vertical).

/* 1. The Parent Container */
.flex-container {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: stretch;
gap: 16px;
}
 
/* Note: Items have NO fixed size on the Cross Axis, allowing them to stretch! */
Main Axis
Cross Axis
.flex-container
1
2
3
!When you toggle flex-direction, notice how the Main Axis and Cross Axis completely swap places!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens to the 'Main Axis' if you set `flex-direction: column`?
  2. 2Which property is responsible for distributing space between items along the Main Axis?
  3. 3If you want to perfectly center a child both horizontally and vertically inside a 'row' container, what two properties do you apply to the parent?

Remember this

  • justify-content aligns items along the Main Axis.
  • align-items aligns items along the Cross Axis.
  • If flex-direction changes to column, the axes swap (justify becomes vertical, align becomes horizontal).
  • space-between pushes the first and last items to the far edges.

Done with this concept?

Mark it complete to track your progress. No login needed.