CSS
Consistent Spacing with Flexbox `gap`
Achieve uniform spacing between flex items and across multiple lines with the `gap` property, eliminating the need for complex margin workarounds.
.flex-gallery {
display: flex;
flex-wrap: wrap;
gap: 20px; /* Applies 20px gap between items both horizontally and vertically */
padding: 20px;
background-color: #f9f9f9;
border: 1px solid #e0e0e0;
}
.gallery-item {
flex: 1 1 calc(33.333% - 20px); /* Adjust basis to account for gap, aiming for 3 items per row */
min-width: 150px; /* Minimum width for items */
background-color: #fff;
border: 1px solid #ccc;
padding: 15px;
text-align: center;
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
box-sizing: border-box; /* Include padding and border in width calculation */
}
/* For responsiveness, adjust basis for fewer items per row */
@media (max-width: 768px) {
.gallery-item {
flex-basis: calc(50% - 20px); /* 2 items per row */
}
}
@media (max-width: 480px) {
.gallery-item {
flex-basis: 100%; /* 1 item per row */
}
}
How it works: This snippet demonstrates the `gap` property in Flexbox, which provides a straightforward way to add consistent spacing between flex items, both horizontally and vertically, without resorting to negative margins or pseudo-elements. It greatly simplifies the management of space, especially when `flex-wrap` is used. The `flex-basis` calculation `calc(33.333% - 20px)` is crucial to account for the `gap` value, ensuring items wrap correctly.