Skip to content
CSS-01Beginner3 min read

Flexbox in practice

The two axes, alignment, and how grow, shrink and basis share space, with a live layout you can tweak.

Updated

Flexbox lays out items along one axis at a time. It is the right tool for navigation bars, toolbars, card footers, centering and any row or column of items that should share space sensibly as the screen size changes.

Two axes

flex-direction sets the main axis. justify-content distributes items along the main axis and align-items positions them on the cross axis. Change the direction and the meaning of both properties rotates with it, which is the single most useful thing to remember about flexbox.

flex-direction
gap
justify-content
align-items
.container {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  gap: 16px;
}
Flexbox playgroundChange each property and watch the three boxes respond. The CSS next to the preview is exactly what is applied to the container.

Alignment values

Valuejustify-contentalign-items
flex-startPack items at the start of the main axisLine items up at the start of the cross axis
centerCenter items along the main axisCenter items on the cross axis
flex-endPack items at the endLine items up at the end
space-betweenFirst and last at the edges, equal gaps betweenNot available
space-evenlyEqual space around every item and both edgesNot available
stretchNot availableFill the cross axis; this is the default

How items share space

The flex shorthand sets three properties at once. flex-basis is the starting size, flex-grow decides who takes extra space, and flex-shrink decides who gives space up when there is not enough to go around.

ShorthandExpands toBehavior
flex: 11 1 0%Share space equally, ignoring content size
flex: auto1 1 autoGrow and shrink, starting from the content size
flex: none0 0 autoKeep the content size and never shrink
flex: 0 0 16rem0 0 16remA fixed 16rem column
layout.css
.layout {
  display: flex;
  gap: 2rem;
}

.sidebar {
  flex: 0 0 16rem; /* never grow or shrink */
}

.content {
  flex: 1;
  min-width: 0; /* lets long content shrink */
}

Common patterns

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

Summary

  • justify-content works on the main axis, align-items on the cross axis.
  • flex-direction decides which axis is which.
  • flex: 1 shares space equally; flex: none keeps an item at its content size.
  • Add min-width: 0 to items that hold long content.

Finished this lesson?

Mark it complete to track your progress across every track in the curriculum.