[toc]
一、 两栏布局:左侧固定 + 右侧自适应
两栏布局通常用于侧边栏导航场景
1. 浮动方案 (Float + Margin)
这是最经典的实现方式。利用浮动让元素并排,再用外边距避开浮动区域
css
.left {
float: left;
width: 200px;
background: tomato;
}
.right {
margin-left: 200px; /* 宽度设为 auto,通过 margin 避开左侧 */
background: gold;
}2. BFC 隔离方案 (Float + Overflow)
利用 BFC(块级格式化上下文)区域不与浮动盒子重叠的特性。
CSS
.left {
float: left;
width: 100px;
background: red;
}
.right {
overflow: hidden; /* 触发 BFC,自动占据剩余空间 */
background: blue;
}3. Flex 布局方案 (推荐)
现代开发首选,代码最简洁,且天然支持等高对齐。
css
.outer {
display: flex;
}
.left {
width: 200px;
flex-shrink: 0; /* 关键:防止左侧在空间不足时被压缩 */
background: tomato;
}
.right {
flex: 1; /* 占据剩余所有空间 */
background: gold;
}4. 绝对定位方案
css
.outer { position: relative; }
.left {
position: absolute;
width: 200px;
background: tomato;
}
.right {
margin-left: 200px;
background: gold;
}二、 三栏布局:左右固定 + 中间自适应
三栏布局要求左右两侧宽度固定,中间部分根据屏幕宽度自动填充
1. Flex 布局实现 (最高效)
利用 Flexbox 的弹性伸缩能力,中间栏设置为 flex: 1
css
.outer {
display: flex;
}
.left { width: 100px; background: tomato; }
.right { width: 100px; background: gold; }
.center {
flex: 1; /* 核心:自动拉伸填充剩余空间 */
background: lightgreen;
}2. 绝对定位实现
左右两栏定位在父级两侧,中间部分通过 margin 预留空间
css
.outer { position: relative; }
.left {
position: absolute;
left: 0; width: 100px;
background: tomato;
}
.right {
position: absolute;
right: 0; width: 200px;
background: gold;
}
.center {
margin-left: 100px;
margin-right: 200px;
background: lightgreen;
}3. 浮动实现 (需注意 HTML 顺序)
利用左右两栏分别向两侧浮动,中间栏利用标准文档流填充。 注意:在 HTML 结构中,必须先写左右两栏,最后写中间栏
css
/* HTML 顺序: .left -> .right -> .center */
.left {
float: left;
width: 100px;
background: tomato;
}
.right {
float: right;
width: 200px;
background: gold;
}
.center {
margin-left: 100px;
margin-right: 200px;
background: lightgreen;
}