CSS
Modern Flexbox Spacing and Alignment
Master efficient spacing and precise alignment within a Flexbox container using the `gap` property for consistent item separation and `justify-content`/`align-items` for overall distribution.
.flex-container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next line */
justify-content: space-between; /* Distributes items along the main axis */
align-items: center; /* Aligns items along the cross axis */
gap: 20px 15px; /* Row gap and column gap */
padding: 20px;
border: 2px dashed #9c27b0;
min-height: 200px;
}
.flex-item {
background-color: #e1bee7;
border: 1px solid #ce93d8;
padding: 15px 25px;
color: #311b92;
font-weight: bold;
border-radius: 5px;
flex-shrink: 0; /* Prevent items from shrinking below content size */
}
.flex-item:nth-child(even) {
min-height: 60px; /* Varying heights to show align-items */
}
/* HTML Structure Example:
<div class="flex-container">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
<div class="flex-item">Item 4 with more text</div>
<div class="flex-item">Item 5</div>
<div class="flex-item">Item 6</div>
</div>
*/
How it works: This snippet demonstrates modern Flexbox for clean spacing and alignment. `display: flex` initializes the flex context. `flex-wrap: wrap` allows items to move to the next line if space runs out. `justify-content: space-between` distributes items with equal space between them along the main axis, while `align-items: center` centers them vertically (on the cross-axis). The `gap: 20px 15px` property (shorthand for `row-gap` and `column-gap`) provides consistent spacing between all flex items, simplifying layout without needing margins on individual items.