I have columns in Bootstrap 5 something like the following.
<div class="row">
<div class="col-md-3 mb-3 border rounded">
<p>Column 1</p>
</div>
<div class="col-md-3 mb-3 border rounded">
<p>Column 2</p>
</div>
<div class="col-md-3 mb-3 border rounded">
<p>Column 3</p>
</div>
<div class="col-md-3 mb-3 border rounded">
<p>Column 4</p>
</div>
</div>
With a border, I can see that there is no spacing between columns. So I changed the top-level <div>
to have class="row gap-3"
.
This correctly gives me a space between each column. However, it also causes the 4th column to wrap.
Is there any way to put a space between each column but not change the number of columns per row?
2
Answers
MrUpsidown’s answer is the preferred solution shown in the Bootstrap documentation. However, column gap can work well with single breakpoints and has simpler html.
Using Gap with Columns
Using gap with fixed size columns causes unwanted column wrapping. The key to making it work is to use auto-sizing columns that adjust to the gap.
By using
col
rather thancol-3
, the columns adjust to fit the available space. If the columns need to flip to rows at a specific breakpoint, then usecol-<breakpoint>
without a column width, e.g.,col-lg
(The demo does not specify a breakpoint so that it works in the snippet.)
Don’t add borders to the columns themselves. Create an element within the column and style this one instead. This way, everything will look just right, at any breakpoint.
You can easily change the width of the gutter with
gx-*
helper classes on therow
element. See https://getbootstrap.com/docs/5.3/layout/gutters/#horizontal-guttersNote that if you are using larger gutters (
.gx-5
), the docs states thatand
What that means is that horizontal scrollbars may appear at certain window sizes if you don’t apply one of these solutions. I would choose the overflow-hidden solution as it doesn’t change the main container padding.