一、圣杯布局/双飞翼布局
布局特点:左右两栏固定宽度,中间部分自适应 三列等高
实现一个左边100px右边150px中间自适应的布局
先来看看效果图:
代码:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>圣杯布局/双飞翼布局</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
text-Align: center;
}
#parents {
width: 1000px;
border: 2px solid;
margin: 0 auto;
}
#top {
background: #666;
height: 50px;
}
#main {
padding-left: 100px;
padding-right: 150px;
overflow: hidden;
}
#left,#content,#right {
padding-bottom: 2000px;
margin-bottom: -2000px;
}
#left {
background: #E79F6D;
float: left;
width: 100px;
position: relative;
left: -100px;
}
#content {
background: #D6D6D6;
float: left;
width: 100%;
margin-left: -100px;
position: relative;
}
#right {
background: #77BBDD;
float: left;
width: 150px;
margin-left: -150px;
position: relative;
left: 150px;
}
#foot {
background: #666;
clear: both;
height: 50px;
}
</style>
</head>
<body>
<div id="parents">
<div id="top">这是Top!</div>
<div id="main">
<div id="left">这是Left!</div>
<div id="content">这是Content!<br><br><br><br>这是多行高度!<br></div>
<div id="right">这是Right!</div>
</div>
<div id="foot">这是Foot!</div>
</div>
</body>
</html>
过程说明:
1.先写一个基本布局
2.将中间left、content和right向左浮动,并设置left和right的宽度分别设置为100px和150px,将三者的父元素的左右内边距设置为100px和150px,与left和right的宽度相同。
3.由于content宽度设置了100%,为content和right设置一个margin-left属性
4.用相对定位把left向左移,right向右移
5.接着处理三列等高的问题:采用padding补偿法:
首先把列的padding-bottom设为一个足够大的值,再把列的margin-bottom设一个与前面的padding-bottom的正值相抵消的负值,父容器设置超出隐藏,这样子父容器的高度就还是它里面的列没有设定padding-bottom时的高度,当它里面的任一列高度增加了,则父容器的高度被撑到它里面最高那列的高度,其他比这列矮的列则会用它们的padding-bottom来补偿这部分高度差。因为背景是可以用在padding占用的空间里的,而且边框也是跟随padding变化的,这样就成功的使得三者列等高了
优点:
- 实现了内容与布局的分离,即Eric提到的Any-Order Columns.
- content部分是自适应宽度的,很容易在定宽布局和流体布局中切换。
- 任何一栏都可以是最高栏,不会出问题。
- 需要的hack非常少(就一个针对ie6的清除浮动hack:_zoom: 1;)
- 在浏览器上的兼容性非常好,IE5.5以上都支持。
二、两栏布局
一栏定宽,一栏自适应
先来看看效果图
代码:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>圣杯布局/双飞翼布局</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
text-Align: center;
}
#parents {
width: 1000px;
border: 2px solid;
margin: 0 auto;
}
#top {
background: #666;
height: 50px;
}
#main {
padding-left: 200px;
overflow: hidden;
}
.left,.right {
padding-bottom: 2000px;
margin-bottom: -2000px;
}
.left{
width: 200px;
background: red;
float: left;
position: relative;
left: -200px;
text-align: center;
color: #fff;
}
.right{
float :left;
width:100%;
position: relative;
margin-left: -200px;
background: yellow;
text-align: center;
}
#foot {
background: #666;
clear: both;
height: 50px;
}
</style>
</head>
<body>
<div id="parents">
<div id="top">这是Top!</div>
<div id="main">
<div class="left">定宽<br><br><br></div>
<div class="right">自适应</div>
</div>
<div id="foot">这是Foot!</div>
</div>
</body>
</html>
说明:
如果会了圣杯布局,那么两栏布局就很简单了