使用position: fixed可实现固定侧边栏。1. 构建HTML结构包含侧边栏和主内容区;2. 为.sidebar设置fixed定位,脱离文档流并固定位置;3. 主内容区通过margin-left留出侧边栏空间;4. 响应式下可用calc()或隐藏菜单优化显示。

使用 CSS 的 position: fixed 可以轻松实现固定侧边栏,让侧边栏在页面滚动时始终保持在可视区域内。下面介绍具体实现方法。
1. 基本结构
先构建一个简单的 HTML 结构,包含一个侧边栏和主内容区域:
2. 使用 position: fixed 定位侧边栏
为侧边栏设置固定定位,使其不随页面滚动而移动:
.sidebar {position: fixed;
top: 0;
left: 0;
width: 200px;
height: 100vh;
background-color: #f4f4f4;
border-right: 1px solid #ddd;
}
说明:
- position: fixed:将元素相对于浏览器窗口固定定位
- top: 0; left: 0:让侧边栏贴住左侧顶部
- width:设定侧边栏宽度
- height: 100vh:高度占满视口,避免滚动时留白
3. 调整主内容区域位置
由于侧边栏脱离文档流,主内容会跑到侧边栏后面,需手动留出空间:
.main-content {margin-left: 200px;
padding: 20px;
}
或者使用 padding-left 或 transform 配合布局。
4. 响应式与兼容性建议
- 在小屏幕上可设为 position: static 或使用汉堡菜单隐藏
- 添加 z-index 确保侧边栏在其他内容之上
- 考虑使用 calc() 动态计算主内容宽度,如:
width: calc(100% - 200px)
基本上就这些。只要掌握 position: fixed 和布局避让,固定侧边栏很容易实现。










