← Back to all snippets
CSS

Evenly Distribute Items with Dynamic Spacing using Flexbox

Efficiently arrange a dynamic number of items, distributing space evenly between them, using Flexbox's `justify-content` and `align-items` for a flexible and responsive layout.

.flex-container {
    display: flex;
    flex-wrap: wrap; /* Allow items to wrap to next line */
    justify-content: space-between; /* Distribute space between items */
    align-items: flex-start; /* Align items at the start of the cross axis */
    gap: 20px; /* Space between items (newer property) */
    padding: 10px;
    background-color: #f9f9f9;
}
.flex-item {
    flex: 0 1 calc(33% - 15px); /* Allows 3 items per row with gap. Adjust as needed. */
    min-width: 150px; /* Minimum width for items */
    background-color: #c9e6ff;
    padding: 15px;
    border-radius: 4px;
    text-align: center;
}
/* Fallback for older browsers without gap support */
@supports not (gap: 1px) {
    .flex-item:not(:nth-child(3n)) { /* For 3 items per row */
        margin-right: 20px;
    }
    .flex-item {
        margin-bottom: 20px;
    }
}
@media (max-width: 768px) {
    .flex-item {
        flex: 0 1 calc(50% - 10px); /* 2 items per row on tablet */
    }
    @supports not (gap: 1px) {
        .flex-item:not(:nth-child(2n)) {
            margin-right: 20px;
        }
        .flex-item:nth-child(3n) { /* Reset for tablet */
            margin-right: 0;
        }
    }
}
@media (max-width: 480px) {
    .flex-item {
        flex: 0 1 100%; /* 1 item per row on mobile */
    }
    @supports not (gap: 1px) {
         .flex-item:not(:nth-child(1n)) { /* Reset for mobile */
            margin-right: 0;
        }
    }
}
How it works: This Flexbox snippet demonstrates how to distribute items evenly within a container, allowing them to wrap onto new lines. `justify-content: space-between` places maximum space between items, while `gap` (or margin fallback for older browsers) adds consistent spacing. The `flex` property on items makes them responsive, adjusting to show 3, 2, or 1 item per row based on screen size using media queries for optimal display.

Need help integrating this into your project?

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

Hire DigitalCodeLabs