Bootstrap双间距问题:如何将并排Div中间间距改为15px?
这个问题我太熟悉了!Bootstrap默认给每个列(col)设置了左右各15px的内边距,相邻两列凑在一起就形成了30px的中间间距。要把这个间距改成15px,根据你用的Bootstrap版本,有几种实用方案:
1. 用Bootstrap 5+的自定义gutter工具类(最简单)
如果你用的是Bootstrap 5.2及以上版本,直接给包裹列的row添加自定义水平gutter类就行。我们要的是两列之间总间距15px,所以给row加gx-[15px],它会自动把每个col的左右内边距设为7.5px,相邻两列加起来刚好15px:
<div class="row gx-[15px]"> <div class="col-lg-9">content here</div> <div class="col-lg-3">content here</div> </div>
如果是Bootstrap 5.2之前的版本,也可以用预设的spacing类(比如gx-2,对应16px,接近15px),或者自定义Sass变量修改全局gutter,但自定义类的方式更灵活。
2. 自定义CSS(兼容所有Bootstrap版本)
要是你用的是Bootstrap 4或者更早,或者不想依赖版本特性,写一段自定义CSS就能搞定:
/* 仅针对lg屏幕下的列调整内边距 */ @media (min-width: 992px) { .custom-gutter .col-lg-9, .custom-gutter .col-lg-3 { padding-left: 7.5px; padding-right: 7.5px; } /* 抵消row默认的负margin,避免内容溢出容器 */ .row.custom-gutter { margin-left: -7.5px; margin-right: -7.5px; } }
然后在HTML里给row加上自定义类:
<div class="row custom-gutter"> <div class="col-lg-9">content here</div> <div class="col-lg-3">content here</div> </div>
这样只会在lg屏幕尺寸下修改间距,其他尺寸保持Bootstrap默认的样式。
3. 先去掉默认gutter,再手动加单边内边距
还有一种思路:先去掉默认的gutter,然后给左边的列右边加15px内边距,这样两列之间就只有这15px的间距了:
<div class="row no-gutters"> <!-- pe-lg-3 表示lg屏幕下右边内边距为15px(默认spacer的3倍) --> <div class="col-lg-9 pe-lg-3">content here</div> <div class="col-lg-3">content here</div> </div>
no-gutters类会移除row的负margin和所有col的默认内边距,然后pe-lg-3精准地给lg屏幕下的左侧列添加右边内边距,完美实现15px的中间间距。
内容的提问来源于stack exchange,提问作者The Hawk
相关产品推荐
相关产品推荐

