源码 点击
简介
- 圣杯布局和双飞翼布局两者是差不多的,最早来自 Matthew Levine 在 2006 年写的一篇文章 《In Search of the Holy Grail》
- 在国内则是由淘宝UED的工程师(玉伯大大)对圣杯布局改进并传播
- 都是为了实现一个两侧宽度固定,中间宽度自适应,且中间栏要先渲染的三栏布局
圣杯布局
圣杯布局的特点
- 三栏布局,搜需要使用浮动
- 因为中间栏要自适应,且要首先渲染,所以要宽度
100%
,且要排在第一个
<style type="text/css">
* {
margin: 0;
padding: 0;
color: #F9F9F9;
}
header,footer{
width: 100%;
height: 100px;
background-color: #666;
}
/* 三栏都需要使用浮动 */
.center,.left,.right{
float: left;
}
/* 左右两栏固定宽度 */
.left,.right{
width: 200px;
height: 500px;/* 高度一般是撑开的 */
background-color: #008000;
}
.container{
/* 给内容区一个高度 */
height: 500px;
}
/* 中间栏 */
.center{
/* 因为需要自适应所以宽度100% */
width: 100%;
height: 500px;
background-color: coral;
}
</style>
</head>
<body>
<header>头部</header>
<div class="container">
<!-- 因为要保证中间栏的首先渲染,所以要先将中间栏放在最前面 -->
<div class="center">中间栏</div>
<div class="left">左栏</div>
<div class="right">右栏</div>
</div>
<footer>底部</footer>
</body>
当上面代码写好的时候是这个样子的
因为中间栏的宽度为100%
将左右两栏挤下去了,然后我们加上这样两行代码
.left{
margin-left: -100%;
}
.right{
margin-left: -200px;
}
盒子就会被我们摆正啦
我们需要是中间栏的内容全部显示出来
.container{
/* 使中间栏的内容全部显示出来 */
padding: 0 200px 0 200px;
}
.left{
margin-left: -100%;
/* 布局摆正之后添加如下代码 */
position: relative;
left: -200px;
}
.right{
margin-left: -200px;
/* 布局摆正之后添加如下代码 */
position: relative;
right: -200px;
}
这样圣杯布局就基本完成了,我问最好给body
一个最小宽度,避免布局塌陷
塌陷的布局
body{
min-width: 1000px;
}
双飞翼布局
双飞翼布局和圣杯布局很相似,唯一不同的是三列摆放的形式,其要求也与圣杯布局相同
- header和footer各自占领屏幕所有宽度,高度固定
- 三栏布局两侧宽度固定不变,中间部分自动填充整个区域
- 中间部分的高度是三栏中最高的区域的高度
<body>
<header>头部</header>
<div class="container">
<div class="center">
<div class="inner">中间栏</div>
</div>
<div class="left">左栏</div>
<div class="right">右栏</div>
</div>
<footer>底部</footer>
</body>
* {
margin: 0;
padding: 0;
color: #F9F9F9;
}
header,footer{
width: 100%;
height: 100px;
background-color: #666;
}
/* 三栏都需要使用浮动 */
.center,.left,.right{
float: left;
}
/* 左右两栏固定宽度 */
.left,.right{
width: 200px;
height: 500px;/* 高度一般是撑开的 */
background-color: #008000;
}
.container{
/* 给内容区一个高度 */
height: 500px;
}
/* 中间栏 */
.center{
/* 因为需要自适应所以宽度100% */
width: 100%;
height: 500px;
background-color: coral;
}
.left{
margin-left: -100%;
}
.right{
margin-left: -200px;
}
body{
min-width: 1000px;
}
回到使用margin
调整的布局
基本的布局已经设置好,圣杯布局和双飞翼布局的区别也就在这里
- 为了使中间部分的内容完全显示出来圣杯布局采用了
- 相对定位
- 容器的内边距
而圣杯布局不采用这种方式,而是在结构上做了手脚,对于中间部分
- 外包容器仍旧是
width:100%
- 而内部容器使用
margin
来调整位置
我们给中间内部的容器加上如下样式
.inner{
/* margin为两边栏的固定宽度 */
margin: 0 200px;
height: 500px;
}
就会发现中间栏的内容全部
双飞翼布局到此完成