1.作用
两者功能相同都是为了实现一个两侧固定,中间自适应的三栏布局
2.圣杯布局和双飞翼布局的区别
圣杯布局 : 为了让中间div内容不被遮挡,将中间div设置了左右padding-left和padding-right后,将左右两个div用相对布局position: relative并分别配合right和left属性,以便左右两栏div移动后不遮挡中间div
双飞翼布局:为了让中间div内容不被遮挡,直接在中间div内部创建子div用于放置内容,在该div里用margin-left和margin-right为左右两栏div留出位置。双飞翼布局把定位优化掉了。
3.圣杯布局相对于双飞翼布局的的优缺点
优点:不需要添加dom节点
缺点:正常情况下没有问题,但是特殊情况下就会暴漏此方案的弊端,如果浏览器无限放大时,圣杯将会破坏掉。当center部分的宽小于right部分时就会发生布局混乱。(center<right即会变形)
4. 双飞翼布局相对于圣杯布局的优缺点
优点: 不会像神杯布局那样变形
缺点 :多加了一层dom 节点
5. 圣杯布局代码
实现步骤:
- 三个容器设置浮动,让他们在一行排列
- 给父元素加内填充,内填充的部分就是放left,right的盒子
- 把left ,right移动到它该去的地方,left 在center 的前面,right 在center的后面
技巧 margin 负值移动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.center,
.left,
.right {
float: left;
height: 200px;
}
.center {
background: red;
width: 100%; // 能不能自适应的关键
}
.left {
width: 200px;
background: green;
margin-left: -100%;
position: relative;
left: -200px;
}
.right {
background: hotpink;
width: 150px;
margin-right: -100%;
}
.father {
padding-left: 200px;
padding-right: 150px;
}
</style>
<body>
<div class="father">
<div class="center"></div>
<div class="left"></div>
<div class="right"></div>
</div>
</body>
</html>
圣杯布局缺点:当center<right 的宽度时变形
6. 双飞翼布局实现
实现步骤
- 给center 的父元素设置100%,给father 内部的三个平级元素设置浮动
- 给center 设置margin-left margin-right 的值用来让left 和right
- left和right用margin 负值效果实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>双飞翼布局</title>
<style>
*{
margin: 0;
padding: 0;
}
.center{
height: 200px;
background: red;
margin-left: 200px;
margin-right: 150px;
}
.center-wrap{
width: 100%;
}
.center-wrap,.left,.right{
float:left;
}
.left{
background: yellow;
height: 200px;
width: 200px;
margin-left: -100%;
}
.right{
background: black;
height: 200px;
width: 150px;
margin-left:-150px;
}
</style>
</head>
<body>
<div class="father">
<div class="center-wrap">
<div class="center"></div>
</div>
<div class="left"></div>
<dov class="right"></dov>
</div>
</body>
</html>