双飞翼布局是前端三栏布局的经典方案,核心要求为左右两侧栏固定宽度,中间主内容栏宽度自适应,且中间栏在HTML结构中优先加载,保证核心内容优先渲染。下面介绍四种常见的CSS实现方式。

方法一:基于float的传统实现
这是双飞翼布局最早的实现方式,核心思路是让中间栏和左右栏都浮动,通过负边距调整左右栏的位置,中间栏内部添加内层容器设置左右边距留出两侧空间。
/* 基础样式重置 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* 三栏公共样式 */
.col {
float: left;
height: 300px;
}
/* 中间栏自适应 */
.center {
width: 100%;
background: #f0f0f0;
}
/* 中间栏内层容器,留出左右空间 */
.center-inner {
margin: 0 200px 0 150px;
height: 100%;
}
/* 左侧栏固定宽度,负边距拉到中间栏左侧 */
.left {
width: 150px;
background: #ffcccc;
margin-left: -100%;
}
/* 右侧栏固定宽度,负边距拉到中间栏右侧 */
.right {
width: 200px;
background: #ccffcc;
margin-left: -200px;
}<div class="container">
<div class="col center">
<div class="center-inner">中间主内容区域,宽度自适应</div>
</div>
<div class="col left">左侧栏,固定150px</div>
<div class="col right">右侧栏,固定200px</div>
</div>方法二:flex弹性布局实现
flex布局是现代CSS常用的布局方式,实现双飞翼布局非常简洁,只需要给容器设置flex属性,左右栏固定宽度,中间栏设置flex:1即可自动占满剩余空间。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
display: flex;
height: 300px;
}
/* 中间栏占满剩余空间 */
.center {
flex: 1;
background: #f0f0f0;
order: 2; /* 保证中间栏在中间显示 */
}
.left {
width: 150px;
background: #ffcccc;
order: 1;
}
.right {
width: 200px;
background: #ccffcc;
order: 3;
}<div class="container"> <div class="center">中间主内容区域,宽度自适应</div> <div class="left">左侧栏,固定150px</div> <div class="right">右侧栏,固定200px</div> </div>
方法三:grid网格布局实现
grid是CSS原生支持的二维布局方案,实现三栏布局只需要定义容器的列宽,中间列设置为auto即可自适应,代码量极少。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
display: grid;
grid-template-columns: 150px auto 200px;
height: 300px;
}
.center {
background: #f0f0f0;
grid-column: 2;
}
.left {
background: #ffcccc;
grid-column: 1;
}
.right {
background: #ccffcc;
grid-column: 3;
}<div class="container"> <div class="left">左侧栏,固定150px</div> <div class="center">中间主内容区域,宽度自适应</div> <div class="right">右侧栏,固定200px</div> </div>
方法四:定位实现
通过绝对定位也可以实现双飞翼布局,给容器设置相对定位,左右栏绝对定位到两侧,中间栏设置左右边距等于左右栏宽度即可。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
position: relative;
height: 300px;
}
.center {
margin: 0 200px 0 150px;
height: 100%;
background: #f0f0f0;
}
.left {
position: absolute;
left: 0;
top: 0;
width: 150px;
height: 100%;
background: #ffcccc;
}
.right {
position: absolute;
right: 0;
top: 0;
width: 200px;
height: 100%;
background: #ccffcc;
}<div class="container"> <div class="center">中间主内容区域,宽度自适应</div> <div class="left">左侧栏,固定150px</div> <div class="right">右侧栏,固定200px</div> </div>
四种方法对比
不同实现方式各有适用场景,具体对比如下:
| 实现方式 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| float传统实现 | 兼容性极好,支持所有浏览器 | 代码相对复杂,需要清除浮动,负边距逻辑较绕 | 需要兼容老版本浏览器的项目 |
| flex实现 | 代码简洁,逻辑清晰,扩展性强 | 不支持IE9及以下版本浏览器 | 现代浏览器项目,快速开发场景 |
| grid实现 | 代码量最少,原生支持二维布局 | 兼容性较差,不支持IE浏览器 | 仅面向现代浏览器的项目 |
| 定位实现 | 逻辑简单,容易理解 | 脱离文档流,高度自适应需要额外处理 | 高度固定的三栏布局场景 |
开发者可以根据项目的浏览器兼容要求和开发效率需求,选择合适的双飞翼布局实现方式。