CSS
Distributing Wrapped Flex Items Evenly Across Multiple Lines
Learn how to use flexbox to efficiently distribute and align items that wrap onto multiple lines, ensuring consistent spacing and visual balance within their container.
.flex-container {
display: flex;
flex-wrap: wrap;
justify-content: space-around; /* Distribute items with space around them */
align-content: flex-start; /* Aligns lines of items at the start of the container */
gap: 15px; /* Space between flex items */
padding: 20px;
border: 2px solid #3498db;
background-color: #ecf0f1;
min-height: 200px;
}
.flex-item {
background-color: #2ecc71;
color: white;
padding: 15px 25px;
text-align: center;
border-radius: 5px;
font-family: sans-serif;
font-size: 1.1em;
flex-basis: auto; /* Allow items to determine their own size */
}
.flex-item:nth-child(even) {
background-color: #e74c3c;
}
.flex-item:nth-child(3n) {
width: 180px;
}
.flex-item:nth-child(4n) {
width: 250px;
}
/* Example usage in HTML:
<div class="flex-container">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3 (Wider)</div>
<div class="flex-item">Item 4 (Wider)</div>
<div class="flex-item">Item 5</div>
<div class="flex-item">Item 6</div>
<div class="flex-item">Item 7</div>
<div class="flex-item">Item 8</div>
</div>
*/
How it works: This snippet demonstrates how to handle flex items that wrap onto multiple lines. By setting `flex-wrap: wrap`, items will break to a new line when there isn't enough space. `justify-content: space-around` distributes items along the main axis with equal space around them, providing visual balance. `align-content: flex-start` controls the spacing between lines of items along the cross axis, aligning them to the start of the container. The `gap` property ensures consistent spacing between items themselves.