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.
.container { display: flex; flex-direction: row; justify-content: flex-start; align-items: center; gap: 16px; }
Alignment values
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.
.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-contentworks on the main axis,align-itemson the cross axis.flex-directiondecides which axis is which.flex: 1shares space equally;flex: nonekeeps an item at its content size.- Add
min-width: 0to items that hold long content.
Finished this lesson?
Mark it complete to track your progress across every track in the curriculum.