如何消除Bootstrap中列元素的垂直间距?
Bootstrap列元素垂直间距消除方案
问题本质
你看到的垂直间距来自浏览器给标题标签(h1、h2)默认添加的margin,而且你尝试设置margin-bottom=20px是反向操作——这会让间距更大,而不是消除。
修复步骤
方案1:用Bootstrap工具类快速解决(推荐)
Bootstrap自带边距控制工具类,直接给对应元素加类即可:
<div class="container-fluid"> <div class="row "> <h1 class="heading mb-0">A Simple database</h1> <h2 class="col-7 mb-0" id="search-section">Search Bar and others</h2> <h2 class="col-5 mb-0" id="result-section">Result</h2> </div> <div class="row mt-0"> <div id="data-box" class="col-7"> <label for="">Search with Serial number :</label> <input type="text" id="search-box" maxlength="5" placeholder="Enter Serial Number"> <input type="submit" value="Submit" id="sub"> </div> <div id="result-box" class="col-5"></div> </div> </div>
mb-0:移除h1、h2的底部外边距mt-0:移除第二行row的顶部外边距
方案2:自定义CSS全局覆盖
如果需要批量修改样式,可以写自定义CSS:
.heading, #search-section, #result-section { margin-bottom: 0; } .row:nth-of-type(2) { margin-top: 0; }
注:如果Bootstrap样式优先级更高,可在属性后加!important强制覆盖。
优化建议:规范Bootstrap布局
Bootstrap的row内建议优先嵌套col元素,把h1放入全宽列中,避免潜在布局问题:
<div class="container-fluid"> <div class="row"> <div class="col-12"> <h1 class="heading mb-0">A Simple database</h1> </div> <h2 class="col-7 mb-0" id="search-section">Search Bar and others</h2> <h2 class="col-5 mb-0" id="result-section">Result</h2> </div> <!-- 下方代码不变 --> </div>
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

