Flexbox gap
December 04, 2021 | TechIf you are like me, you've had many situations where you haven't been able to use CSS grid. Most often it was because of Internet Explorer support. There are a lot of reasons to use flexbox in other cases as well. And you can get a good results using flexbox. But there was the annoying issue of having to use margins between the elements. For a three-column flex grid, you would have to remove the margin from every third item. That is if you wanted to have the grid items from edge to edge in the container. And then you need to probably have a two-column version for narrower screens... and so the margin and nth-child fun begins. I sometimes tried to have margins all around each item. But this usually ended up causing more issues than solving. This is not impossible, but at least I find it annoying when I know how easy it could be. I've built many sites using flexbox. But it always felt somewhat sad to know that with grid, you could define a gap and things would work out of the box.
I have good news for you! Did you know that flexbox also supports gap nowadays? All major browsers apart from Internet Explorer support this feature. I hope you don't have to support that browser anymore. I had missed the fact that this became available for Safari as well in April 2021 already. Luckily my fiancé sent me a video Stop Using Margins With Flexbox from Web Dev Simplified on YouTube.
The flexbox code below is completely valid and the best part is that it also works!
.wrapper { display: flex; flex-flow: row wrap; gap: 2rem; }
I created a really quick CodePen for the flexbox gap, you can see it in action.
I personally can't wait to get rid of the margin game with flexbox.
Photo by Kelly Sikkema on Unsplash