css制作侧边栏
使用CSS制作侧边栏
固定定位侧边栏
通过position: fixed实现侧边栏固定位置,适合导航菜单等场景:
.sidebar {
position: fixed;
top: 0;
left: 0;
width: 250px;
height: 100vh;
background: #2c3e50;
color: white;
padding: 20px;
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
}
弹性布局侧边栏
结合Flexbox布局创建响应式侧边栏:
.container {
display: flex;
min-height: 100vh;
}
.sidebar {
flex: 0 0 200px;
background: #34495e;
color: white;
}
.main-content {
flex: 1;
padding: 20px;
}
可折叠侧边栏
通过CSS过渡效果实现侧边栏折叠功能:
.sidebar {
width: 250px;
height: 100%;
transition: all 0.3s ease;
}
.sidebar.collapsed {
width: 60px;
}
.toggle-btn {
cursor: pointer;
padding: 10px;
text-align: center;
}
响应式侧边栏
使用媒体查询适配不同屏幕尺寸:
.sidebar {
width: 300px;
float: left;
}
@media (max-width: 768px) {
.sidebar {
width: 100%;
float: none;
}
}
悬浮效果侧边栏
为侧边栏添加交互效果:

.sidebar-item {
padding: 12px 15px;
transition: background 0.2s;
}
.sidebar-item:hover {
background: rgba(255,255,255,0.1);
}
.active {
background: #3498db;
border-left: 3px solid white;
}
注意事项
- 固定定位侧边栏需要考虑z-index层级
- 移动端需处理侧边栏的显示/隐藏逻辑
- 确保侧边栏高度与内容区域匹配
- 使用CSS变量便于主题颜色管理






