CSS
Distribute and Align Uneven Items in a Flex Container
Master distributing space between items and aligning elements with varying heights in a Flexbox container, ensuring consistent visual appeal for dynamic content layouts.
.flex-container {
display: flex;
justify-content: space-around; /* Distributes space around items */
align-items: center; /* Vertically centers items */
gap: 15px; /* Adds space between items, modern alternative to padding/margin */
padding: 20px;
background-color: #f9f9f9;
border: 1px solid #ddd;
min-height: 150px;
}
.flex-item {
background-color: #d1ecf1;
padding: 10px 15px;
border-radius: 5px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
/* Height variations for demonstration */
height: auto;
min-height: 50px;
}
.flex-item:nth-child(2) { min-height: 80px; }
.flex-item:nth-child(3) { min-height: 60px; }
How it works: This Flexbox snippet efficiently arranges a series of items within a container, even if they have different heights. `display: flex;` enables Flexbox. `justify-content: space-around;` distributes space evenly around each item, ensuring they are separated and centered within the available space. `align-items: center;` vertically aligns all items to the center of the flex container's cross-axis, creating a visually balanced row despite varying item heights. The `gap` property provides consistent spacing between the items.