To set the distance between flexbox items in CSS, you can use the following methods:
1. Use the gap Property (Modern Browsers)
The simplest and most intuitive way to add spacing between flex items.
.container {
display: flex;
gap: 20px; /* Adds 20px between all flex items */
}
- Works for both rows and columns (use
row-gaporcolumn-gapindividually if needed). - No extra margins: Avoids unintended spacing at the edges of the container.
- Browser Support: Supported in all modern browsers (Chrome 84+, Firefox 63+, Safari 14.1+). Not supported in IE11.
2. Use Margins on Flex Items
Add margins directly to the flex items (e.g., margin-right or margin-left):
.container {
display: flex;
}
.item {
margin-right: 20px; /* Adds space between items */
}
/* Remove margin from the last item */
.item:last-child {
margin-right: 0;
}
- Flexibility: Use
margin,padding, or a combination. - Responsive Control: Adjust margins for different screen sizes.
3. Use justify-content to Distribute Space
Control spacing by distributing space between/around items (doesn’t set fixed gaps):
.container {
display: flex;
justify-content: space-between; /* Distributes space between items */
}
- Options:
space-between: Equal space between items (no edge spacing).space-around: Equal space around items (half-space at edges).space-evenly: Equal space around and between items.
Example Comparison
| Method | Code Example | Pros | Cons |
|---|---|---|---|
gap | gap: 20px | Clean, no edge spacing | No IE11 support |
| Margins | .item:not(:last-child) { margin-right: 20px } | Full control, backward-compatible | Requires manual edge-case handling |
justify-content | justify-content: space-between | Distributes available space | Doesn’t set fixed gaps |
Recommended Workflow
- For modern browsers: Use
gapfor simplicity. - For legacy support: Use margins with
:not(:last-child). - For dynamic spacing: Combine
justify-contentwith margins orgap.
Code Demo
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
<style>
.container {
display: flex;
gap: 20px; /* Modern method */
}
/* OR */
.item:not(:last-child) {
margin-right: 20px; /* Legacy method */
}
</style>
Choose the method that best fits your browser requirements and design goals!