Control Multi-line Layout with align-content
Use align-content with flex-wrap to control how multiple lines of flex items are spaced and aligned within the container's cross axis.
Detailed Explanation
Multi-line Alignment with align-content
align-content controls the distribution of space between and around flex lines when the container has multiple lines of items (i.e., when flex-wrap: wrap is set and items actually wrap). It has no effect on single-line flex containers.
CSS Code
.container {
display: flex;
flex-wrap: wrap;
align-content: space-between;
height: 400px;
}
.item {
flex: 0 0 30%;
}
How It Works
When items wrap, they form multiple flex lines. align-content determines how those lines are positioned along the cross axis. Think of it as justify-content but for the cross axis and for lines (groups of items) rather than individual items.
align-content Values
| Value | Effect |
|---|---|
stretch |
Lines stretch to fill the container (default) |
flex-start |
Lines packed to the start of the cross axis |
flex-end |
Lines packed to the end of the cross axis |
center |
Lines centered in the cross axis |
space-between |
Equal space between lines; no space at edges |
space-around |
Equal space around each line |
align-content vs align-items
This is one of the most commonly confused pairs in Flexbox:
- align-items: Controls how individual items are aligned within their line along the cross axis.
- align-content: Controls how the lines themselves are distributed along the cross axis.
align-items works on single-line and multi-line containers. align-content only has a visible effect when there are multiple lines.
Practical Example
A card grid with flex-wrap: wrap and align-content: flex-start ensures cards start at the top of the container without stretching to fill the full height, which is usually the desired behavior for wrapped grids.
Use Case
Use align-content when building wrapped flex layouts like card grids, tag clouds, or responsive image galleries where items flow onto multiple lines. It controls vertical spacing between rows of items in a wrapped flex container.