调整带居中标题的Bootstrap导航栏(navbar)折叠触发的屏幕宽度
问题根源
你遇到的导航链接提前换行问题,核心是两点配置错误:
- 给
.customHead设置100%宽度直接占满了导航栏全部水平空间,再加上给.navbar-collapse设置了固定25%宽度,不足以放下右侧三个导航链接,自然会提前换行。 - 用float属性修改Bootstrap原生导航栏布局,Bootstrap 4+的导航栏默认采用flex布局,float会破坏原生的空间计算逻辑,导致折叠触发时机不符合预期。
修复方案
调整后的CSS代码(直接替换原有样式即可)
.navbar-collapse { background-color: red; } .navbar-nav, .nav-link{ background-color: yellow; color: red !important; } /* 用flex占品牌和导航链接之间的剩余空间,内部居中显示标题 */ .customHead { flex: 1; display: flex; justify-content: center; align-items: center; background: red; } text { background: orange; } /* 自定义折叠断点,max-width数值越大,折叠触发时机越早,按需调整即可 */ @media only screen and (max-width: 1300px) { .customHead { width: auto; } .navbar-toggler { background-color: red; } /* 覆盖Bootstrap默认xl断点的展开规则 */ .navbar-expand-xl .navbar-collapse { display: none !important; } .navbar-expand-xl .navbar-toggler { display: block !important; } .navbar-expand-xl .collapse.show{ display: block !important; width: 100%; } }
HTML代码无需修改,注意确保页面已引入Bootstrap对应的JS和jQuery依赖,折叠功能依赖这两个脚本才能正常运行。
内容的提问来源于stack exchange,提问作者KarkMump
相关产品推荐
相关产品推荐

