CSS
Consistent Spacing for Flex Items with the gap Property
Utilize the modern CSS `gap` property to create consistent spacing between flex items. This eliminates the need for complex margin-based solutions that can lead to extra space at container edges.
.flex-container {
display: flex;
flex-wrap: wrap;
gap: 15px; /* Applies a 15px gap between flex items */
padding: 10px;
background-color: #e0e0e0;
}
.flex-item {
background-color: #d0d0d0;
padding: 15px;
border: 1px solid #c0c0c0;
}
How it works: The `gap` property provides a much cleaner and more intuitive way to add spacing between flex items, avoiding common issues with margins. By setting `gap: 15px` on the flex container, all direct children (flex items) will have a 15px space between them, both horizontally and vertically if `flex-wrap` is active. This eliminates the need for negative margins on the container or complex `margin-right: last-child` selectors, simplifying responsive layouts.