双飞翼布局与圣杯布局(详细)
双飞翼布局
双飞翼布局的特点:三列布局,左右固定,中间自适应。
实现双飞翼布局的方法有很多:BFC,定位,flex(弹性),浮动。
这里我们重点讲浮动实现的双飞翼布局
双飞翼布局采用margin-left负值,以及浮动来实现。
先写布局:
<body>
<div id="head"></div>
<div id="main">
<div class="center"> <!-- 先写center中间 -->
<p>内容部分</p>
</div>
<div class="left"></div>
<div class="right"></div>
</div>
</body>
<style>
*{margin: 0;padding: 0;}
#head{width:100%;height:100px;background: darkorange;}
#main{width:100%;height:300px;}
#main .center{width:100%;float: left;height: 100%;}
#main .center p{background:red;margin:0 200px 0 150px;height:100%;}
#main .left{width:150px;height:100%;background: darkseagreen;float: left;
margin-left: -100%;}
#main .right{width:200px;height:100%;background: gold;float:left;margin-left: -200px;}
</style>
双飞翼布局总结如下:
1、双飞翼的布局特点是先写center中间部分,让主体内容先输出。
2、让center,left,right三个容器都左浮动。
3、让left与right利用margin-left负值移动到center左右两侧指定位置。
4、然后让center上的内容部分,利用margin固定在中间,把左右margin的位置空出来。
5、将背景颜色加到内容部分
圣杯布局
与双飞翼布局相比,圣杯布局代码量更少。
圣杯布局是经过双飞翼布局代码的简单更改,来实现的。
以下是更改后的圣杯布局代码:
<div id="head"></div>
<div id="main">
<div class="center">
内容部分 <!-- 去掉了p标签 -->
</div>
<div class="left"></div>
<div class="right"></div>
</div>
*{margin: 0;padding: 0;}
.clear:after{content: "";display: block;clear: both;}
#head{width:100%;height:100px;background: darkorange;}
#main{;margin:0 200px 0 150px;background:red;height:200px;}
#main .center{width:100%;float: left;height: 100%;}
#main .left{width:150px;height:100%;background: darkseagreen;float: left;
margin-left: -100%;position: relative;left:-150px;}
#main .right{width:200px;height:100%;background: gold;float:left;margin-left: -200px;position: relative;right:-200px;}
圣杯布局总结如下:
1、圣杯布局不需要center子标签。
2、原来固定p标签的margin放到了.main上。
3、将.left与.right用相对定位,放到左右两边的位置上。
4、由于定位+浮动,影响.head的效果。因此,需要用伪类清除浮动。(overflow:hidden放到.main上没用)
双飞翼布局偏向于对内容居中展示,双飞翼布局偏向于于对整个父标签居中,再将两边的块定位到左右两侧。