圣杯和双飞翼指的是中间固定两边自适应的三栏布局方法。具体代码介绍如下:
一、圣杯布局
html片段:
<header>这是页面的头部份</header>
<div id="container">
<div id="main" class="col">这是圣杯布局</div>
<div id="left" class="col">left</div>
<div id="right" class="col">right</div>
</div>
<footer>这是页面的底部</footer>
html片段:
header{
width: 100%;
height: 50px;
background-color: lightcoral;
color: lightslategrey;
text-align: center;
line-height: 50px;
}
footer{
width: 100%;
height: 50px;
background-color: black;
color: lightcoral;
text-align: center;
line-height: 50px;
}
.col{
float: left;
position:relative;
}
#left{
width: 200px;
height: 400px;
background-color: lightblue;
margin-left: -100%;
left: -200px;
}
#right{
width: 200px;
height: 400px;
background-color: lightblue;
margin-left: -200px;
right: -200px;
}
#main{
width: 100%;
height: 400px;
background-color: lightpink;
}
#container{
height: 400px;
padding: 0 200px;
}
三个col都设置float: left,为了把left和right定位到左右部分,采用负边距,left部分margin-left: -100%,right部分margin-right: -200px。当设置完了之后,虽然左右栏定位成功,但是中间main的内容会被遮盖住。所以在main的父元素container中设置左右padding值。给所有col设置position: relative,再分别给左右栏添加left、right值,使他们定位到正确位置。
效果图如下:
二、双飞翼布局
html片段:
<body>
<header>这是页面的头部分</header>
<div id="container">
<div id="main" class="col">
<div id="main-wrap">
这是双飞翼布局。
</div>
</div>
<div id="left" class="col">left</div>
<div id="right" class="col">right</div>
</div>
<footer>这是页面的底部</footer>
</body>
css样式:
header{
width: 100%;
height: 50px;
background-color: lightcoral;
color: lightslategrey;
text-align: center;
line-height: 50px;
}
footer{
width: 100%;
height: 50px;
background-color: black;
color: lightcoral;
text-align: center;
line-height: 50px;
}
.col{
float: left;
}
#left{
width: 200px;
height: 400px;
background-color: lightblue;
margin-left: -100%;
}
#right{
width: 200px;
height: 400px;
background-color: lightblue;
margin-left: -200px;
}
#main{
width: 100%;
height: 400px;
background-color: lightpink;
}
#main-wrap{
margin: 0 200px;
}
#container{
height: 400px;
}
与圣杯布局一样,一开始三个col都设置float: left,为了把left和right定位到左右部分,采用负边距,left部分margin-left: -100%,right部分margin-right: -200px。
之后就是处理main中内容的遮盖问题,只需设置main-wrap的左右外边距即可解决。
相比圣杯布局,双飞翼不必设置左右栏的position: relative,也不必设置左右left、right值,只需多添加一个子元素包含,并添加相应的margin。
效果图如下: