圣杯布局其实和双飞翼布局都是三栏布局,两边的盒子宽度固定,中间盒子自适应。它们实现的效果是一样的,差别在于其实现的思想。
1.圣杯布局
父元素的的三栏务必先写中间盒子,因为中间盒子要被优先渲染。
<div class="header">Header</div>
<div class="bd">
<div class="main">Main</div>
<div class="left">Left</div>
<div class="right">Right</div>
</div>
<div class="footer">Footer</div>
- 第一步:
写三个盒子的样式
.left{
background: #E79F6D;
width:150px;
float:left;
}
.main{
background: #D6D6D6;
width:100%;
float:left;
}
.right{
background: #77BBDD;
width:190px;
float:left;
}
- 第二步:
让左右的盒子都上去,利用负边距,需要设置左盒子的左边距为负的中间盒子的宽度(中间盒子宽度100%所以设置左边.left {margin-left:-100%;}),这样左盒子才可以往最左边移动。需要设置右盒子其左边距为负的自己的宽度(右盒子宽度190px),也就是.right {margin-left:-200px;},这样右盒子才可以在一行的最右边显示出自己。
.left{
background: #E79F6D;
width:150px;
float:left;
margin-left:-100%;
}
.right{
background: #77BBDD;
width:190px;
float:left;
margin-left:-190px;
}
- 第三步
这时候中间的盒子被左右挡住了,给外层加padding,利用父级元素设置左右内边距的值,把父级的三个子盒子往中间挤。
.bd{
padding-left:150px;
padding-right:190px;
}
- 第四步
这时候整个三个盒子都向中间挤了,所以要将左右盒子进行相对定位。移动自己的宽度。
.left{
background: #E79F6D;
width:150px;
float:left;
margin-left:-100%;
position: relative;
left:-150px;
}
.right{
background: #77BBDD;
width:190px;
float:left;
margin-left:-190px;
position:relative;
right:-190px;
}
- 整体的代码
<html>
<head>
<style type="text/css">
.header,.footer{
height:30px;
width:100%;
background:black;
clear:both; /*--------这里要注意-----------*/
}
.bd{
padding-left:100px;
padding-right:120px;
}
.main{
width:100%;
height:200px;
background:purple;
color:white;
float:left;
}
.left{
width:100px;
height:200px;
background:yellow;
margin-left:-100%;
float:left;
position:relative;
left:-100px;
}
.right{
width:120px;
height:200px;
background:yellow;
margin-left:-120px;
float:left;
position:relative;
right:-120px;
}
</style>
</head>
<body>
<div class="header">header</div>
<div class="bd">
<div class="main">main</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
<div class="footer">footer</div>
</body>
</html>
2.双飞翼布局
双飞翼布局是圣杯布局的一个改进不使用相对布局,增加多一个div。
<div class="header">Header</div>
<div class="bd">
<div class="main">
<div class="inner">
Main
</div>
</div>
<div class="left">Left</div>
<div class="right">Right</div>
</div>
<div class="footer">Footer</div>
样式到圣杯布局的第二步,然后对新增的div添加样式
.bd{
/*padding-left:150px;*/
/*padding-right:190px;*/
}
.left{
background: #E79F6D;
width:150px;
float:left;
margin-left:-100%;
/*position: relative;*/
/*left:-150px;*/
}
.main{
background: #D6D6D6;
width:100%;
float:left;
}
.right{
background: #77BBDD;
width:190px;
float:left;
margin-left:-190px;
/*position:relative;*/
/*right:-190px;*/
}
.inner{
margin-left:150px;
margin-right:190px;
}