本文介绍一种纯 css 方案,通过 `position: sticky` 结合嵌套容器布局,使左侧导航栏中的顶部和底部区域在页面滚动时始终保持可见,无需 javascript,且能自动适配含固定头部的布局。
在构建现代响应式布局时,常需实现「左侧固定宽度导航栏 + 顶部固定 Header + 右侧主内容可滚动」的三栏结构。但一个典型痛点是:若直接给 .sider 设置 height: 100vh,其内部的“TOP SIDER”和“BOTTOM SIDER”会随视口高度拉伸,无法智能避让顶部 Header;而设为 100% 又因父容器无显式高度而失效。
核心思路:不控制 .sider 的整体高度,而是让其内部关键子元素独立“粘性定位”。CSS 的 position: sticky 允许元素在滚动范围内保持相对位置——top: 0 使其贴顶,bottom: 0 使其贴底,二者共存于同一 flex 容器中,借助 flex-direction: column 和 justify-content: space-between 实现自然分离。
以下是优化后的完整实现:
Fixed Header (Sticky)
Top Navigation
Bottom Tools
Main Content Area
This section scrolls independently. Try scrolling up/down — you’ll notice that "Top Navigation" stays pinned just below the header, and "Bottom Tools" remains fixed at the bottom of the viewport — all without JavaScript.
End of content
✅ 关键要点说明:
该方案轻量、语义清晰、完全基于 CSS,兼顾可维护性与性能,是构建专业管理后台左侧导航的理想实践之一。