如何在<nav>标签内正确使用Bootstrap 4网格系统?
这个问题我之前也碰到过!核心原因是Bootstrap的navbar组件自带了默认的内边距(padding),再加上navbar-toggler按钮的默认样式,会和你手动加的row/col网格系统的间距规则冲突,导致布局偏移不对称。
下面给你两种可行的修复方案,按需选择:
方案1:利用Navbar原生的Flex布局(推荐)
Bootstrap的Navbar本身就是一个flex容器,完全不需要嵌套row/col就能实现你要的三分布局,代码更简洁,也不会有样式冲突:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <nav class="navbar navbar-dark bg-dark text-white d-flex justify-content-between align-items-center"> <!-- 左侧按钮 --> <button class="navbar-toggler" type="button" id="menu-toggle"> <span class="navbar-toggler-icon"></span> </button> <!-- 中间标题,用mx-auto让它居中 --> <span class="mx-auto">main title</span> <!-- 右侧内容 --> <div class="text-right">right</div> </nav>
解释一下:
d-flex确保Navbar是flex布局(其实Bootstrap 4的Navbar默认就是flex,但显式加上更稳妥)justify-content-between让左右两个元素贴边,中间元素自动填充空间mx-auto给中间的标题设置左右自动margin,确保它始终水平居中,不受左右元素宽度影响
方案2:保留Row+Col,修复样式冲突
如果你一定要用row和col的结构,需要清除Navbar和Toggler的默认样式干扰:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <nav class="navbar navbar-dark bg-dark text-white p-0"> <!-- 移除Navbar默认左右padding --> <div class="row no-gutters w-100"> <!-- no-gutters消除row负margin和col间距,w-100让row占满Navbar宽度 --> <div class="col-2 d-flex align-items-center"> <!-- d-flex让按钮垂直居中 --> <button class="navbar-toggler" type="button" id="menu-toggle"> <span class="navbar-toggler-icon"></span> </button> </div> <div class="col-8 d-flex align-items-center justify-content-center"> <!-- 垂直+水平居中 --> main title </div> <div class="col-2 d-flex align-items-center justify-content-end"> <!-- 垂直+右对齐 --> right </div> </div> </nav>
关键调整点:
- 给Navbar加
p-0,移除默认的左右内边距,避免和col的宽度叠加导致布局偏移 - 给row加
no-gutters,消除row默认的左右负margin和col之间的间距 - 给每个col加
d-flex align-items-center,确保内部内容垂直居中(因为Navbar有默认高度,不加的话内容会贴顶部) - 给row加
w-100,确保它占满Navbar的整个宽度
两种方案都能解决你遇到的不对称问题,个人更推荐方案1,因为更贴合Bootstrap的组件设计思路,后期维护也更方便~
内容的提问来源于stack exchange,提问作者frianH
相关产品推荐
相关产品推荐

