Stop Using Margin in Flexbox, Use Gap Instead
Here’s why you should use Gap in Flexbox instead of Margin.
While building web applications, every one of us must have encountered a scenario where we have to add some spacing b.w.
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-bottom to our
flex-box items. If we add this CSS to
flex-items we will get the desired layout:
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.
We can also use the Chrome inspect tool to see the difference.
We have a CSS property called
gap which works with both
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
Suppose we have this layout:
Which renders like this:
Now, to add spacing we can leverage the
Gap Shorthand Property:
And there you have it. Thank you for reading.