gap
Sets the space between the children of a Flexbox or Grid container. Replaces the hack of canceling outer spacing with negative margins with a single declaration.
Modern approach
Space is added only between adjacent children. Since none is added at the outer edges, you need neither negative margins to cancel it nor a wrapper. It works the same way in Grid.
.tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
<ul class="tags">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>Legacy approach
Each child got half the margin, and the parent’s negative margin canceled the part that stuck out at the edges. A wrapper with overflow: hidden was also needed to keep the negative margin from spilling out.
.tags-wrapper {
overflow: hidden;
}
.tags {
display: flex;
flex-wrap: wrap;
margin: -4px;
}
.tags > li {
margin: 4px;
}
<div class="tags-wrapper">
<ul class="tags">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</div>Things to watch when replacing
- In Grid, it has worked in all browsers since October 2017 (then named
grid-gap). In Flexbox, it works from Chrome 84, Firefox 63, and Safari 14.1 (April 2021). - Dropping the negative margins also lets you remove the wrapper’s
overflow: hidden. Focus outlines and shadows on edge children are no longer clipped. grid-gapis the old name forgapand still works as an alias. Feel free to rename it togapwhen you find it.gapis the minimum space.justify-content: space-betweenor margins on the children make the space wider.
Browser Support
Chrome
v57+2017-03-09Edge
v16+2017-10-17Safari
v10.1+2017-03-27Safari (iOS)
v10.3+2017-03-27Firefox
v52+2017-03-07