行业知识
css【详解】—— 圣杯布局 vs 双飞翼布局 (含手写清除浮动 clearfix)
2026-11-01 09:35:48
来源:互联网转载
两者功能index.php/tags-41973.html" >���果相同,实现方式不同
效果预览
- 两侧宽度固定,中间宽度自适应(三栏布局)
- 中间部分优先渲染
- 允许三列中的任意一列成为最高列
圣杯布局
通过左右栏填充容器的左右 padding 实现,更多细节详见注释。
css 圣杯布局 body { /* 清除浏览器默认样式 */ margin: 0; /* 设置最小宽度 */ min-width: 550px; } .header { background-color: gray; height: 40px; } .container { /* 圣杯布局 -- 通过 padding 实现 */ padding-left: 200px; padding-right: 150px; } .center { /* center宽度自适应 */ width: 100%; float: left; background-color: yellow; height: 100px; } .left { width: 200px; float: left; margin-left: -100%; position: relative; right: 200px; background-color: blue; height: 100px; } .right { width: 150px; float: left; margin-right: -150px; background-color: red; height: 100px; } .footer { /* 清除浮动 */ clear: both; background-color: gray; height: 40px; } header center left right footer双飞翼布局
通过左右栏填充主体内容的左右 margin 实现,更多细节详见注释。
css 双飞翼布局 body { /* 清除浏览器默认样式 */ margin: 0; /* 设置最小宽度 */ min-width: 550px; } .header { background-color: gray; height: 40px; } .container { /* 自适应宽度 */ width: 100%; /* 左浮动 */ float: left; } .center { /* 双飞翼布局 -- 通过 margin 留白实现 */ margin-left: 200px; margin-right: 150px; background-color: yellow; height: 100px; } .left { width: 200px; /* 左浮动 */ float: left; /* 自身向左移动父元素(此处为body)宽度的 100% */ margin-left: -100%; background-color: blue; height: 100px; } .right { width: 150px; /* 左浮动 */ float: left; /* 自身向左移动 150px */ margin-left: -150px; background-color: red; height: 100px; } .footer { /* 清除浮动 */ clear: both; background-color: gray; height: 40px; } header center left right footer手写清除浮动 clearfix
/* 手写 clearfix */.clearfix:after { content: ""; display: table; clear: both;}.clearfix { *zoom: 1; /* 兼容 IE 低版本 */}用在类似圣杯布局的容器上,footer 不再需要 clear: both;
css 圣杯布局 body { /* 清除浏览器默认样式 */ margin: 0; /* 设置最小宽度 */ min-width: 550px; } .header { background-color: gray; height: 40px; } .container { /* 圣杯布局 -- 通过 padding 实现 */ padding-left: 200px; padding-right: 150px; } .center { /* center宽度自适应 */ width: 100%; float: left; background-color: yellow; height: 100px; } .left { width: 200px; float: left; margin-left: -100%; position: relative; right: 200px; background-color: blue; height: 100px; } .right { width: 150px; float: left; margin-right: -150px; background-color: red; height: 100px; } .footer { /* 清除浮动 */ /* clear: both; */ background-color: gray; height: 40px; } /* 手写 clearfix */ .clearfix:after { content: ""; display: table; clear: both; } .clearfix { *zoom: 1; /* 兼容 IE 低版本 */ } header center left right footer