CSS
Distribute Items Evenly with Flexbox `gap` and `justify-content`
Efficiently manage horizontal spacing and alignment for a set of items within a container using CSS Flexbox `justify-content` and the modern `gap` property for clean layouts, including wrapping items.
.flex-row-container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next line */
justify-content: space-between; /* Distributes items with space between them */
gap: 20px; /* Space between flex items, both row and column */
padding: 20px;
border: 1px solid #ccc;
}
.flex-item {
flex: 0 0 calc(33.33% - 20px); /* Example: 3 items per row with gap consideration */
background-color: #ffe0b2;
padding: 15px;
text-align: center;
border: 1px solid #ffcc80;
}
/* For demonstration, adjusting flex-item basis slightly to account for gap */
@media (max-width: 768px) {
.flex-item {
flex: 0 0 calc(50% - 10px); /* 2 items per row on medium screens, adjusted for gap */
}
}
@media (max-width: 480px) {
.flex-item {
flex: 0 0 100%; /* 1 item per row on small screens */
}
}
How it works: This snippet showcases how to distribute items evenly within a flex container using `justify-content: space-between`. The modern `gap` property provides consistent spacing between all flex items, simplifying layout compared to traditional margin techniques. `flex-wrap: wrap` allows items to move to the next line when space is insufficient. The `flex` property on `.flex-item` is used to create a responsive grid-like behavior, calculating item width while accounting for the `gap` to maintain proper distribution across different screen sizes.