如何缩小Bootstrap单行内列之间的间距
解决Bootstrap行内列间距过大的问题
嘿,我看你在调整Bootstrap列间距的时候遇到了麻烦——明明用了container,但四个功能块之间的空隙还是太大,不符合你的需求,对吧?这其实是Bootstrap默认的列内边距(gutter)在搞鬼,默认的.col-*类自带左右各15px的padding,这就是间距大的核心原因。下面给你几个实用的解决办法,结合你的代码来改,很快就能搞定!
方法1:自定义CSS缩小列的内边距
最直接的方式就是覆盖Bootstrap默认的列padding,你可以写一个自定义类,然后给目标列加上:
/* 自定义列间距类,数值按需调整 */ .tight-col { padding-left: 6px; padding-right: 6px; }
然后在你的HTML里,给每个col-lg-3都加上这个类:
<div class="col-sm-12 col-md-6 col-lg-3 tight-col"> <!-- 你的图标和文字 --> </div>
你可以随便改6px这个数值,直到间距符合你的预期为止。
方法2:用Bootstrap内置的间距工具(推荐Bootstrap 5+)
如果你用的是Bootstrap 5,官方已经提供了现成的gutter调整类,直接给.row加个g-*类就行:
比如把你的row改成:
<div class="row text-center boxesText g-1">
这里的g-1表示设置行内列的间距为0.5rem(Bootstrap的间距系统从g-0到g-5,数字越小间距越紧凑),你可以试试g-0或者g-2,找到最适合的效果。
方法3:调整内部盒子的外边距(不改动列结构)
要是你不想碰列的padding,也可以给你的.b1盒子加左右margin,让内部的图标块更紧凑:
.b1{ width: 80px; height: 80px; background-color: aqua; border-radius: 4px; margin: 0 auto; position: relative; /* 加左右margin,缩小内部元素的间距 */ margin-left: 8px; margin-right: 8px; }
不过这种方法不如前两种直接,适合不想改动列布局的场景。
针对你代码的完整修改示例
我用方法1+方法2结合(假设你用Bootstrap 5),给你改好了代码,你直接替换试试:
修改后的CSS
body{ padding: 0; margin: 0; background-image: url('Main backgrounds/cool-background\ (1).png'); background-size: cover; height: 100%; font-family: 'Montserrat'; overflow-x: hidden; } .heading{ color: white; text-align: center; padding-top: 15px; } .boxesText{ color: white; } .b1{ width: 80px; height: 80px; background-color: aqua; border-radius: 4px; margin: 0 auto; position: relative; } i{ font-size: 45px; text-align: center; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -webkit-filter: drop-shadow(5px 5px 5px #222); filter: drop-shadow(-5px 10px 7px #222); } .spacer{ height: 6px; } .notification .badge { position: absolute; top: -10px; right: -10px; padding: 5px 10px; border-radius: 50%; background-color: red; color: white; } /* 自定义紧凑列间距 */ .tight-col { padding-left: 5px; padding-right: 5px; }
修改后的HTML
<div class="container"> <div class="row text-center boxesText g-1"> <div class="col-sm-12 col-md-6 col-lg-3 tight-col"> <div class="b1"> <i class="fa fa-comment" style="margin-top: -4px; margin-left: 2px;"></i> </div> <div class="spacer"></div> <span>Discuss</span> </div> <div class="col-sm-12 col-md-6 col-lg-3 tight-col"> <div class="b1"> <i class="fa fa-calendar-o"></i> </div> <div class="spacer"></div> <span>Booking</span> </div> <div class="col-sm-12 col-md-6 col-lg-3 tight-col"> <div class="b1"> <i class="fa fa-edit" style="margin-left: 4px;"></i> </div> <div class="spacer"></div> <span>Invoice</span> </div> <div class="col-sm-12 col-md-6 col-lg-3 tight-col"> <div class="b1"> <i class="fa fa-gear"></i> </div> <div class="spacer"></div> <span>Settings</span> </div> </div> </div>
调整完之后,你可以根据实际显示效果微调g-1和tight-col里的数值,直到达到你想要的紧凑感。
内容的提问来源于stack exchange,提问作者RANA
相关产品推荐
相关产品推荐

