← Back to all snippets
CSS

Vertical Distribution of Flex Items with `align-content`

Understand and apply `align-content` in Flexbox to control how space is distributed *between* multiple lines of flex items vertically, ideal for multi-row layouts.

/* HTML Structure for context:
<div class="flex-container">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
    <div class="item">10</div>
</div>
*/

body {
    font-family: Arial, sans-serif;
    display: flex;
    flex-direction: column;
    gap: 20px;
    align-items: center;
    padding: 20px;
}

.flex-container {
    display: flex;
    flex-wrap: wrap; /* Essential for align-content to work */
    width: 300px; /* Fixed width to force wrapping */
    height: 400px; /* Fixed height to create available space vertically */
    border: 2px dashed #92b0c9;
    background-color: #e0f2f7;
    padding: 10px;
    margin-bottom: 20px;

    /* Experiment with these values: */
    /* align-content: flex-start; */
    /* align-content: flex-end; */
    /* align-content: center; */
    /* align-content: space-between; */
    /* align-content: space-around; */
    align-content: stretch; /* Default, stretches lines to fill space */

    /* Optional: align items horizontally within their lines */
    justify-content: flex-start;
}

.item {
    background-color: #6daee1;
    color: white;
    padding: 15px;
    margin: 5px;
    width: 80px; /* Fixed width to ensure wrapping */
    text-align: center;
    border-radius: 5px;
}

/* Example specific for demonstrating align-content: */
.flex-container:nth-of-type(2) {
    align-content: space-between;
}
.flex-container:nth-of-type(3) {
    align-content: center;
}
How it works: This snippet demonstrates the `align-content` Flexbox property, which is crucial for controlling how space is distributed *between* multiple lines of flex items along the cross-axis. Unlike `align-items` (which aligns individual items within their line), `align-content` only applies when `flex-wrap: wrap` is active and there's extra space in the cross-axis (vertical, in a `flex-direction: row` container). Values like `space-between`, `space-around`, `center`, `flex-start`, `flex-end`, and `stretch` allow precise control over the vertical spacing and alignment of entire rows of flex items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs