CSS Flexbox and CSS Grid are fantastic tools available for managing layout on the Web. Flexbox handles single-dimensional layouts very well while CSS Grid handles two-dimensional layouts with columns and rows. Often we want to add space between the items within our layout. This post will show how to do this using the CSS gap
property in Flexbox and the necessary workarounds for reasonable browser support.
Inline Flex
To demonstrate CSS Gap, we will use Flexbox. CSS Gap works in CSS Grid, but there are many cases where we have inline lists that need space without a defined grid.
<div class="flex-gap">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
.flex-gap {
display: inline-flex;
flex-wrap: wrap;
}
We use inline-flex
so we can have flex items but display our parent element as an inline element instead of a block element. The flex-wrap: wrap
property will allow our items to wrap as the parent container shrinks or is constrained.
If we want to add space between each item, we could use margin on each item.
.flex-gap {
display: inline-flex;
flex-wrap: wrap;
}
.flex-gap > div {
margin: 6px;
}
Margins works but is not the same behavior as CSS Gap space. Notice the extra space surrounding the boxes. With gap spacing, we only want space applied between the items. Using CSS Gap, we can achieve this.
.flex-gap {
display: inline-flex;
flex-wrap: wrap;
gap: 12px;
}
CSS Gap is a feature of the CSS Grid spec and Flexbox; however, currently, only Firefox is the only major browser that supports gap
on flex items.
Because of the lack of browser support, to achieve the same effect we will need to use some CSS hacks with margins.
<div class="emulated-flex-gap">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
.emulated-flex-gap > * {
margin: 12px 0 0 12px;
}
.emulated-flex-gap {
display: inline-flex;
flex-wrap: wrap;
margin: -12px 0 0 -12px;
width: calc(100% + 12px);
}
We can set margin space on the top and left of each item. On the flex parent element, we can use negative margins to counter the excess margin on the outer elements to get a similar effect to CSS gap
space.
We can clean up the CSS a bit by using CSS Custom Properties so it is easierto change the margin spacing.
.emulated-flex-gap {
--gap: 12px;
display: inline-flex;
flex-wrap: wrap;
margin: calc(-1 * var(--gap)) 0 0 calc(-1 * var(--gap));
width: calc(100% + var(--gap));
}
.emulated-flex-gap > * {
margin: var(--gap) 0 0 var(--gap);
}
With this workaround, we can get something close to CSS Gap space in all browsers. I hope to soon see improved browser support for CSS gap
as it enhances managing layouts with CSS. With CSS Gap spacing, we can remove a lot of white space complexities in CSS when using margins. Check out the full working demo!
Top comments (0)