CSS

Controlling Multi-Line Flex Item Spacing with `align-content` and `flex-wrap`

Optimize layouts with `flex-wrap: wrap` by leveraging `align-content` to precisely distribute and space multiple lines of flex items within their container.

.flex-container {
    display: flex;
    flex-wrap: wrap; /* Essential for align-content to take effect */
    width: 300px; /* Constrain width to force wrapping */
    height: 400px; /* Give container height for align-content to work */
    border: 2px dashed #3f51b5;
    background-color: #e8eaf6;
    padding: 10px;

    /* Controls vertical spacing between lines when items wrap */
    /* Options: stretch (default), flex-start, flex-end, center, space-between, space-around, space-evenly */
    align-content: space-between;
    /* Try align-content: center; or align-content: space-around; */
}

.flex-item {
    width: 80px;
    height: 80px;
    margin: 5px; /* Margin to separate items within a line */
    background-color: #7986cb;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.2em;
}
How it works: When flex items wrap onto multiple lines using `flex-wrap: wrap`, the `align-content` property determines how these lines are spaced and distributed vertically within the flex container. It works similarly to `justify-content` but operates across lines rather than within a single line. This snippet demonstrates how `align-content` can be used to control the distribution of multiple wrapped flex lines, ensuring a balanced or desired vertical layout within the container.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs