三栏布局是前端开发中常见的经典布局模式,通常指左右两栏固定宽度,中间一栏自适应(圣杯布局或双飞翼布局)。以下是多种实现方式,从传统到现代,全面覆盖。
一、什么是三栏布局?
- 左侧栏:固定宽度(如 200px),常用于导航或侧边栏。
- 中间栏:自适应,占据剩余空间,是主要内容区域。
- 右侧栏:固定宽度(如 150px),常用于广告或辅助信息。
✅ 目标:中间栏宽度随浏览器窗口变化自动调整。
二、实现方式
✅ 方式 1:Flexbox 布局(推荐 ⭐⭐⭐⭐⭐)
现代布局首选,代码简洁,兼容性好。
<div class="container">
<div class="left">左侧固定</div>
<div class="center">中间自适应</div>
<div class="right">右侧固定</div>
</div>
.container {
display: flex;
height: 100vh;
}
.left {
width: 200px;
background: #f0f0f0;
}
.center {
flex: 1; /* 占据剩余所有空间 */
background: #ddd;
}
.right {
width: 150px;
background: #f0f0f0;
}
✅ 优点:
- 无需浮动或定位
- 天然支持垂直居中、等高列
- 响应式友好(可结合
flex-wrap)
✅ 方式 2:CSS Grid 布局(现代推荐 ⭐⭐⭐⭐⭐)
更强大的二维布局方案。
.container {
display: grid;
grid-template-columns: 200px 1fr 150px; /* 左中右 */
height: 100vh;
}
/* 或使用 minmax() 实现更灵活的自适应 */
grid-template-columns: 200px minmax(0, 1fr) 150px;
✅ 优点:
- 一行代码定义布局
- 支持复杂网格
1fr表示“一份可用空间”,完美实现自适应
✅ 方式 3:浮动 + margin(传统方法 ⭐⭐)
使用 float 和 margin 实现,需注意清除浮动。
.container {
overflow: hidden; /* 创建 BFC,清除浮动 */
}
.left {
float: left;
width: 200px;
margin-left: -100%; /* 将左栏拉到最左 */
}
.center-wrap {
float: left;
width: 100%;
}
.center {
margin: 0 150px 0 200px; /* 为左右栏留出空间 */
}
.right {
float: left;
width: 150px;
margin-left: -150px; /* 将右栏拉到最右 */
}
❌ 缺点:
- 代码复杂
- 需清除浮动
- 不推荐用于新项目
✅ 方式 4:绝对定位(特定场景 ⭐⭐)
适用于脱离文档流的布局,如弹窗、固定侧边栏。
.container {
position: relative;
height: 100vh;
}
.left {
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 100%;
}
.center {
margin: 0 150px 0 200px; /* 留出左右空间 */
}
.right {
position: absolute;
right: 0;
top: 0;
width: 150px;
height: 100%;
}
❌ 缺点:脱离文档流,影响其他元素布局
✅ 方式 5:圣杯布局(Holy Grail Layout)(经典 ⭐⭐)
使用浮动 + 负边距 + 包含块 padding 实现。
<div class="container">
<div class="center">中间</div>
<div class="left">左</div>
<div class="right">右</div>
</div>
.container {
padding: 0 150px 0 200px; /* 为左右栏留空间 */
overflow: hidden;
}
.center, .left, .right {
float: left;
}
.center {
width: 100%;
}
.left {
width: 200px;
margin-left: -100%;
position: relative;
left: -200px;
}
.right {
width: 150px;
margin-left: -150px;
}
❌ 缺点:结构与样式耦合,维护困难
✅ 方式 6:双飞翼布局(Double Wing Layout)(经典 ⭐⭐)
在圣杯基础上优化,避免使用 position。
<div class="main-wrap">
<div class="center">中间</div>
</div>
<div class="left">左</div>
<div class="right">右</div>
.main-wrap {
float: left;
width: 100%;
}
.center {
margin: 0 150px 0 200px;
}
.left {
float: left;
width: 200px;
margin-left: -100%;
}
.right {
float: left;
width: 150px;
margin-left: -150px;
}
三、面试加分点
| 点位 | 说明 |
|---|---|
| 🌟 现代首选 Flex/Grid | 推荐使用 flex 或 grid,语义清晰,维护简单 |
| 🌟 响应式扩展 | 可结合媒体查询,在小屏时变为单列布局 |
🌟 1fr 的含义 | Grid 中 1fr 表示“一份可用空间”,是自适应的关键 |
| 🌟 等高列 | Flex 和 Grid 天然支持等高,无需额外处理 |
| 🌟 BFC 清除浮动 | 使用 overflow: hidden 防止高度塌陷 |
✅ 总结对比表
| 方法 | 实现难度 | 推荐度 | 适用场景 |
|---|---|---|---|
| Flexbox | 简单 | ⭐⭐⭐⭐⭐ | 通用、响应式 |
| Grid | 简单 | ⭐⭐⭐⭐⭐ | 复杂布局 |
| 浮动 + margin | 复杂 | ⭐⭐ | 兼容老浏览器 |
| 绝对定位 | 中等 | ⭐⭐ | 固定布局 |
| 圣杯/双飞翼 | 复杂 | ⭐ | 学习经典布局思想 |
💬 一句话总结:
“现代开发中,优先使用 Flexbox 或 CSS Grid 实现三栏布局,代码简洁、语义清晰、响应式友好;传统浮动方法仅用于兼容或学习目的。”
在面试中,能清晰对比多种方案,并推荐最佳实践,会显得你具备扎实的布局能力和现代开发思维。
THE END


