Stop Using Margin in Flexbox, Use Gap Instead

Here’s why you should use Gap in Flexbox instead of Margin.

Hello World!

While building web applications, every one of us must have encountered a scenario where we have to add some spacing b.w. flex-box items.

Let’s understand this by an example. Suppose we have this condensed layout.

And we want to have some spacing b.w. these small boxes. Like this:

We generally achieve it by adding margin-right or margin-bottom to our flex-box items. If we add this CSS to flex-items we will get the desired layout:

margin-right: 20px;
margin-bottom: 20px;

The Problem:

At one glance it seems OK, but when we go deeper we will see the issue with the above approach:
1. Extra margin-right is added to the corner divs (which is not required)
2. Extra margin-bottom is added to the bottom row divs (which is not required

Why it is not visible? Because we have a white background in which the container div is blending, as soon as we change the background color of .containerto something else, we will start seeing the difference.

Extra space at right and bottom of div

We can also use the Chrome inspect tool to see the difference.

The Solution:

We have a CSS property called gap which works with both flexbox and grids . It is also supported by a majority of browsers.

By using gap we can add horizontal and vertical properties to a flexbox and grid items. Here I am demonstrating it with flexbox only.

Suppose we have this layout:

<div className='container'>
<div />
<div />
.
.
<div />
</div>

Which renders like this:

Now, to add spacing we can leverage the gap property:

CSS gap — gap

Gap Shorthand Property:

CSS GAP — row-gap and column-gap

And there you have it. Thank you for reading.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store