如何让Bootstrap 5页面的标题/导航固定在视口顶部?
解决Bootstrap 5垂直导航+标签页固定顶部问题
要让标题和垂直导航始终固定在屏幕顶部/左侧,不受标签页内容高度变化影响,只需调整布局结构并利用Bootstrap 5的定位类即可实现,具体修改如下:
核心修改步骤
- 将标题设置为顶部固定定位,确保始终显示在视口顶部,同时给页面主体添加顶部内边距避免内容被遮挡。
- 将垂直导航设置为左侧固定定位,可选择垂直居中或顶部对齐,导航项过多时添加滚动条避免超出视口。
- 调整标签页内容区域的偏移,给固定导航留出空间,保证内容正常显示。
修改后的完整代码
<body style="padding-top: 80px;"> <!-- 为顶部固定标题留出空间 --> <!-- 固定顶部的标题容器 --> <div class="container-fluid position-fixed top-0 start-0 w-100 bg-dark" style="width: 90% !important; z-index: 1030;"> <h1 class="text-center text-white display-4 py-3 mb-0">Header</h1> </div> <div class="container-fluid" style="width: 90%"> <div class="row"> <!-- 固定左侧的垂直导航 --> <div class="col-md-3 position-fixed top-50 start-0 translate-middle-y" style="z-index: 1030;"> <nav class="nav flex-column nav-pills nav-pills-custom" id="navTab" role="tablist" style="max-height: calc(100vh - 120px); overflow-y: auto;"> <a class="nav-link active" data-bs-toggle="pill" href="#first-tab" role="tab" aria-selected="true">Link 1</a> <a class="nav-link" data-bs-toggle="pill" href="#last-tab" role="tab" aria-selected="false">Link 7</a> </nav> </div> <!-- 标签页内容区域,偏移左侧导航宽度 --> <div class="col-md-9 offset-md-3"> <div class="tab-content" id="tabContent"> <div class="tab-pane fade show active shadow rounded bg-white p-5" id="first-tab" role="tabpanel"> <h4 class="font-italic mb-4">First Tab</h4> <p class="font-italic text-muted mb-2">Short content.</p> </div> <div class="tab-pane fade shadow rounded bg-white p-5" id="last-tab" role="tabpanel"> <h4 class="font-italic mb-4">Last Tab</h4> <p class="font-italic text-muted mb-2">Longer content.</p> <!-- 示例长内容,测试滚动 --> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> </div> </div> </div> </div> </body>
关键修改说明
- 标题固定:使用
position-fixed top-0 start-0 w-100实现全宽顶部固定,设置z-index:1030确保在内容之上,添加背景色避免内容穿透。 - 导航固定:用
position-fixed top-50 start-0 translate-middle-y让导航垂直居中,max-height和overflow-y:auto保证导航项过多时可滚动。 - 内容偏移:内容区域添加
offset-md-3,匹配左侧导航的宽度,避免内容被导航遮挡。 - 标签页链接修正:原代码中标签页链接的
href缺少#,修正为href="#first-tab"才能正确切换标签。
内容的提问来源于stack exchange,提问作者rte76
相关产品推荐
相关产品推荐

