传统的三栏布局主要是圣杯布局和双飞翼布局。主要是,中间布局自适应,两边盒子宽度固定。
1.圣杯布局实现的思想
- 中间盒子的宽度设置为 width: 100%; 独占一行;
- 使用负边距(均是 margin-left)把左右两边的盒子都拉上去和中间盒子同一行;
.left {margin-left:-100%;} 把左边的盒子拉上去
.right {margin-left:-右边盒子宽度px;} 把右边的盒子拉上去 - 父盒子设置左右的 padding 来为左右盒子留位置;
- 对左右盒子使用相对布局来占据 padding 的空白,避免中间盒子的内容被左右盒子覆盖;
代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{ margin:0;padding:0; }
header{ width:100%;height:40px;background:darkseagreen; }
.container{ height:200px; overflow: hidden; padding:0 200px; }
.middle{ width:100%; height:200px; background: blue; float: left; }
.left{ width:200px; height:200px; background: #CCFF33; float: left; margin-left:-100%; position: relative; left: -200px; }
.right{ width:200px; height:200px; background: darkorchid; float: left; margin-left:-200px; position: relative; right:-200px; }
footer{ width:100%; height:30px; background: darkslateblue; }
</style>
</head>
<body>
<header><h4>header内容区</h4></header>
<div class="container">
<div class="middle"><h4>中间弹性区</h4></div>
<div class="left"><h4>左边栏</h4></div>
<div class="right"><h4>右边栏</h4></div>
</div>
<footer class="footer"><h4>footer内容区</h4></footer>
</body>
</html>
2. 双飞翼布局
实现思想是父盒子包含三个纸盒子(左中右),中间的子盒子里再加一个子盒子。
- 中间盒子的宽度设置为 width: 100%; 独占一行;
- 使用负边距(均是 margin-left)把左右两边的盒子都拉上去和中间盒子同一行;
- 在中间盒子里面再添加一个 div,然后对这个 div 设置 margin-left 和 margin-right来为左右盒子留位置;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{ margin:0;padding:0; }
header{ width:100%;height:40px;background:darkseagreen; }
.container{ height:200px; overflow: hidden; }
.middle-inner{margin:0 200px;}
.middle{ width:100%; height:200px; background: blue; float: left; }
.left{ width:200px; height:200px; background: #CCFF33; float: left; margin-left:-100%; }
.right{ width:200px; height:200px; background: darkorchid; float: left; margin-left:-200px;}
footer{ width:100%; height:30px; background: darkslateblue; }
</style>
</head>
<body>
<header><h4>header内容区</h4></header>
<div class="container">
<div class="middle">
<div class="middle-inner">
<h4>中间弹性区</h4>
</div>
</div>
<div class="left"><h4>左边栏</h4></div>
<div class="right"><h4>右边栏</h4></div>
</div>
<footer class="footer"><h4>footer内容区</h4></footer>
</body>
</html>
实现效果
以上内容主要参考http://brianway.github.io/2017/05/18/css-layout-classical-problems/#利用浮动实现