圣杯布局&双飞翼布局

都是三列的思想,中间主内容区域自适应,左右两列固定宽度。

主要为了加强关于css布局的理解

圣杯布局

html代码
1
2
3
4
5
6
7
8
9
10
11
12
<div id="head">
<h1>head</h1>
</div>
<div id="container">
<div id="center" class="column">center</div>
<div id="left" class="column">left</div>
<div id="right" class="column">right</div>
</div>

<div id="footer">
<h1>footer</h1>
</div>

主区域center放在前面优先渲染

css
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
 #container {
padding-left: 200px;
padding-right: 150px;
}

#container .column {
float: left;
position: relative;
}

#center {
width: 100%;
background:#eee;
}
#left {
width: 200px;
margin-left: -100%;
right: 200px;
}
#right {
width: 150px;
margin-right: -150px;
}
#footer {
clear: both;
}
思路整理
  • 中间三列浮动定位float: left
  • 主内容设置padding-left与padding-right用于放置左右两列(设置margin也可),同时用position:relative定位
  • 左列设置margin-left:-100%;使left与center部分重合,然后设置right:200px;使其相对自身左移宽度值,这样,左列就定位在了center为其预留的位置上
  • 右列设置margin-right为自身负宽度值,使右列定位在center为其预留位置上。

要点:

  • relative定位
  • 负margin的运用

双飞翼布局

html
1
2
3
4
5
6
7
8
9
<div class="header">header</div>
<div class="content">
<div class="middle">
<div class="inner-middle">middle</div>
</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
<div class="footer">footer</div>

双飞翼布局在主内容区域外层多嵌套了一个div

css
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.content {
overflow: hidden;
}

.middle {
width: 100%;
float: left;
}
.inner-middle {
widows: 100%;
margin-left: 100px;
margin-right: 100px;
}

.left {
width: 100px;
float: left;
margin-left: -100%;
}
.right {
width: 100px;
float: left;
margin-left: -100px;
}
思路整理
  • 主内容外层嵌套一个div,外层div宽度为100%,内层div设置margin-left与margin-right为左右两列预留位置
  • 左列采用margin-left:-100%将左列顶上
  • 右列margin-left: -100px将右列顶上

要点:

  • 主内容外层嵌套一个div
  • 左右两列采用负margin

两种布局比较

  • 圣杯布局是在为主内容(left+content+right)设置一个边距,采用==relative定位==及==负margin值==,使左右两列定位到为其预留的位置上
  • 双飞翼布局是在==主要显示区域(content)外面嵌套上一层div==,外层div宽度为100%,内层(content)为左右列预留位置,左右两列采用==负margin值==定位到相应位置