1.圣杯布局
① 圣杯布局的实现步骤:
- 定义好header和footer的width,使之横向撑满;
- 将container中的三列设为左浮动;
- 把左右两列分别定宽200px和150px;
- 由于浮动的关系,此时的center会占据整个container,左右两块区域会被挤下去
- 接下来设置left的 margin-left: -100%,让left回到上一行的最左侧
- 但此时会把center给遮住了,所以这时给外层的container设置 padding-left和padding-right,给left和right空出位置;
- 这时的left并没有在最左侧,所以通过设置相对定位(position: relative;)和right: 200px,把left拉回到最左侧;
- 相同的,对于right区域,设置 margin-right: -150px,把right拉回第一行的右侧;
- 最后,给浮动的元素容器添加一个clearfix的class,实现在此元素之后添加一个看不见的块元素清理浮动。
② 圣杯布局的代码如下所示:
<!DOCTYPE html>
<html>
<head>
<title>圣杯布局</title>
<style type="text/css">
body {
min-width: 550px;
}
#header {
background-color: #f1f1f1;
text-align: center;
}
#container { /*为了防止中间内容被两侧覆盖,通过设置padding-left和padding-right,给left和right空出位置。*/
padding-left: 200px;
padding-right: 150px;
}
#container .column {
float: left; /*将container中的三列设为浮动*/
}
#center {
background-color: #ccc;
width: 100%; /*让center横向撑满*/
}
#left {
position: relative;
background-color: red;
width: 200px; /*设置左侧边栏的宽度为200px*/
margin-left: -100%; /*让左侧边栏和中间内容横向重叠,主要是为了让left回到上一行从左侧*/
right: 200px;
}
#right {
background-color: red;
width: 150px; /*设置右侧边栏的宽度为150px*/
margin-right: -150px;
}
#footer {
text-align: center;
background-color: #f1f1f1;
}
.clearfix:after {
content: '';
display: table;
clear: both;
}
</style>
</head>
<body>
<div id="header">this is header</div>
<div id="container" class="clearfix">
<div id="center" class="column">this is center</div>
<div id="left" class="column">this is left</div>
<div id="right" class="column">this is right</div>
</div>
<div id="footer">this is footer</div>
</body>
</html>
③ 圣杯布局的运行结果如下图:
2.双飞翼布局
① 双飞翼布局的实现步骤:
- 将container中的三列设为左浮动;
- 设置center宽度为100%,使之横向撑满;
- 设置负边距,left设置负边距为100%,right设置负边距为自身宽度;
- 设置center-wrap的margin值为左右两个侧栏留出空间,margin值大小为left和right宽度。
② 双飞翼布局的代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>双飞翼布局</title>
<style type="text/css">
body {
min-width: 550px;
}
.col {
float: left;
}
#center {
width: 100%;
height: 250px;
background-color: #ccc;
}
#center-wrap {
margin: 0 200px 0 200px;
}
#left {
width: 200px;
height: 250px;
background-color: yellow;
margin-left: -100%;
}
#right {
width: 200px;
height: 250px;
background-color: yellow;
margin-left: -200px;
}
</style>
</head>
<body>
<div id="center" class="col">
<div id="center-wrap">this is center</div>
</div>
<div id="left" class="col">this is left</div>
<div id="right" class="col">this is right</div>
</body>
</html>
③ 双飞翼布局的运行结果如下所示:
3.圣杯布局和双飞翼布局要点总结
- 使用float布局
- 两侧使用margin负值,以便和中间内容横向重叠
- 为了防止中间内容被两侧覆盖,圣杯布局用padding留白,双飞翼布局用margin留白