Bootstrap 5: Perfect Gaps Between Buttons
Let’s say, you have a bunch of buttons that you would like to evenly space out. It looks fine when it’s only a single row:
However, once you load it up on your phone, they suddenly cramp together:
Naturally, you might add .mb-1 class to create vertical gaps. It works, but now the vertical and horizontal spacings are a tiny bit different, and it also creates an unwanted margin at the bottom:
This might be unnoticeable, BUT you’re a perfectionist, what would you do?
.d-flex with Gaps
The .d-flex CSS class has already existed for a while, it is used to turn the container into a Flexbox. But the .gap-n classes were only been introduced in Bootstrap 5.
Now, just make the container a Flexbox using .d-flex, and then use .flex-wrap for overflow wrapping and .gap-1 to set the gaps, done! Perfect gaps, no more bottom margin:
In plain CSS, it is equivalent to:
#button-container {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
}
As usual, the .gap-n classes come in 5 sizes by default:
- .gap-1: 0.25rem
- .gap-2: 0.5rem
- .gap-3: 1.0rem
- .gap-4: 1.5rem
- .gap-5: 3rem
…so, you may enlarge the gaps by increasing the number. Here’s one with .gap-2:
The catch is, browser support for Flexbox gap may not be high enough, as at the moment it’s still at about 92%.
If you have a friend who is still holding an iPhone 12 (released in 2020) or older, chances are he/she may still be using iOS earlier than version 14.5, which doesn’t support Flexbox gap, if the OS updates never get to run.
I DO have several such friends, but I’m pretty sure that it will only take another 2 years to confidently use the gap property everywhere. Meanwhile, I’m already using it in most of our internal systems as I know exactly which browser my colleagues are using.
Have fun!