三栏布局之圣杯布局

在学习HTML和CSS的一些总结和经验,供大家参考和学习,同时也欢迎大家参与讨论。

圣杯布局

前言: 圣杯布局双飞翼布局是前端面试时常问的问题,因为它既能体现你懂HTML结构又能体现出你对HTML+CSS布局的掌握。事实上,圣杯布局其实和双飞翼布局是一回事。它们实现的都是三栏布局,两边的盒子宽度固定,中间盒子自适应,也就是我们常说的固比固布局。它们实现的效果是一样的,差别在于其实现的方法。

首先我们来看一下效果图

Alt text

第一步:构建页面结构

1
2
3
4
5
6
7
<div id="header">头部</div>
<div id="container">
<div id="center" class="column">主要内容</div>
<div id="left" class="column">次要内容</div>
<div id="right" class="column">侧边栏</div>
</div>
<div id="footer">页脚</div>

第二步:为各个容器添加背景和高度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
body{
min-width: 500px;
margin: 0;
padding: 0;
text-align: center;/*文本居中*/
}
#container .column{
height: 500px;
}
#center{
background: #cecece;
}
#left{
background: red;
}
#right{
background: orange;
}
#header,
#footer {
background: gray;
height: 50px;
}

第三步:为各个容器添加宽度和为container(主要内容)添加内边距

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
body{
min-width: 550px;
margin: 0;
padding: 0;
text-align: center;/*文本居中*/
}
#container{
padding-left: 300px;/*左内边距*/
padding-right: 200px;/*右内边距*/
}
#container .column{
height: 400px;
}
#center{
background: #cecece;
width: 100%;
}
#left{
background: red;
width: 300px;
}
#right{
background: orange;
width: 200px;
}
#header,
#footer {
background: gray;
height: 50px;
}

效果图如下

Alt text

1
2
3
4
5
6
7
#container .column{
height: 300px;
float: left;
}
#footer{
clear: both;
}

效果图如下

Alt text

第五步:让次要内容(left)移到左边

首先为其容器添加相对定位

1
2
3
4
5
#container .column{
height: 300px;
position: relative;/*相对定位*/
float: left;
}

其次,我们让次要内容(left)的外负边距设为-100%(因为主要内容的宽度为100%)

1
2
3
4
5
#left{
background: red;
width: 300px;
margin-left: -100%;
}

效果图如下

Alt text

在利用在相对定位的情况下,右移动300px

1
2
3
4
5
6
#left{
background: red;
width: 300px;
margin-left: -100%;
right: 300px;
}

效果图如下

Alt text

第六步:同样的道理,让侧边栏(right)移到右边

1
2
3
4
5
#right{
background: orange;
width: 200px;
margin-right: -200px;
}

最终效果图如下

Alt text

提醒:是不是已经get到技能了,接下来,你们可以利用浏览器的开发工具(F12)测试一下效果,看是不是,中间自适应,两旁固定宽度



文章标题: 三栏布局之圣杯布局
文章作者: 王奕聪,QQ:1301842163
许可协议: 知识共享许可协议
©署名-非商用-相同方式共享 4.0