CSS align-content in Multi-Line Flexbox
The CSS align-content property manages the alignment and
spacing of entire flex lines along the cross axis within a flex
container. This article explains what align-content does,
how it differs from other alignment properties, and the specific
prerequisites required for it to take effect in multi-line Flexbox
layouts.
What is the
align-content Property?
In CSS Flexbox, align-content defines how extra space is
distributed between and around flex lines along the cross axis (the axis
perpendicular to the main axis defined by
flex-direction).
While align-items aligns individual flex items within
their respective flex line, align-content treats each row
or column of items as a single unit and positions those units relative
to the container.
Common values for align-content include:
stretch(default): Lines stretch to take up the remaining space.flex-start/start: Lines are packed tightly toward the start of the cross axis.flex-end/end: Lines are packed tightly toward the end of the cross axis.center: Lines are grouped together in the center of the cross axis.space-between: Lines are evenly distributed; the first line is flush with the start, and the last line is flush with the end.space-around: Lines are evenly distributed with equal space around each line.space-evenly: Lines are distributed so that the space between any two adjacent lines, and the space to the edges, is identical.
When Does
align-content Apply?
The align-content property only has a visual effect when
two specific conditions are met simultaneously:
1. The
Container Must Allow Wrapping (flex-wrap: wrap)
By default, flex containers are single-line containers
(flex-wrap: nowrap). In a single-line layout, there is only
one flex line, rendering align-content completely
ineffective. For align-content to work, wrapping must be
explicitly enabled using:
.container {
display: flex;
flex-wrap: wrap; /* or wrap-reverse */
}Additionally, there must be enough flex items with sufficient size to force the content to break into two or more lines.
2. There Must Be Surplus Space on the Cross Axis
align-content requires available space along the cross
axis to distribute the lines. If the height of the flex container (in a
row-based layout) shrinks to fit its content tightly, there is no empty
space to distribute, and changing align-content will
produce no visible change.
To activate the property, the container must have an explicit cross-axis dimension that is larger than the combined cross-axis size of the flex lines:
.container {
display: flex;
flex-wrap: wrap;
height: 500px; /* Provides extra cross-axis space in row direction */
align-content: space-between;
}If flex-direction is set to column or
column-reverse, the cross axis becomes horizontal, meaning
the container must have an explicit width or
min-width that exceeds the combined width of the wrapped
columns.