How to Use Gap in Flexbox: Simple CSS Spacing Guide
Use the
gap property on a flex container to add consistent space between flex items without extra margins. It works like grid gaps but applies to flex layouts, making spacing simpler and cleaner.Syntax
The gap property sets the space between flex items inside a flex container. You can specify one or two values:
gap: 10px;adds 10 pixels of space between all items.gap: 10px 20px;adds 10 pixels horizontally and 20 pixels vertically.
This property works only on flex containers (display: flex; or inline-flex).
css
.flex-container {
display: flex;
gap: 15px;
}Example
This example shows a flex container with three colored boxes spaced evenly using gap. The gap adds space between the boxes without needing margin on each item.
css
html, body {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
font-family: Arial, sans-serif;
}
.container {
display: flex;
gap: 20px;
background-color: #f0f0f0;
padding: 20px;
border-radius: 8px;
}
.box {
width: 80px;
height: 80px;
background-color: #4a90e2;
border-radius: 6px;
display: flex;
justify-content: center;
align-items: center;
color: white;
font-weight: bold;
font-size: 1.2rem;
}Output
<div class="container"><div class="box">1</div><div class="box">2</div><div class="box">3</div></div>
Common Pitfalls
Some common mistakes when using gap in flexbox include:
- Using
gapon containers that are not flex or grid; it won't work. - Expecting
gapto add space outside the container; it only adds space between items. - Trying to use
row-gaporcolumn-gapwithout proper browser support (mostly supported now).
Before gap support in flexbox, developers used margins on flex items, which can cause uneven spacing or require extra wrappers.
css
/* Wrong: gap on non-flex container */ .container { gap: 20px; /* No effect if display is block */ } /* Right: gap on flex container */ .container { display: flex; gap: 20px; }
Quick Reference
| Property | Description | Example |
|---|---|---|
| gap | Sets space between flex items | gap: 10px; |
| row-gap | Sets vertical space between items | row-gap: 15px; |
| column-gap | Sets horizontal space between items | column-gap: 20px; |
| display | Must be flex or inline-flex for gap to work | display: flex; |
Key Takeaways
Use
gap on flex containers to add space between items easily.gap replaces the need for margins on flex items for spacing.gap works only if display is set to flex or inline-flex.You can set vertical and horizontal gaps separately with
row-gap and column-gap.Check browser support but modern browsers fully support
gap in flexbox.