圣杯布局与双飞翼布局


简介

圣杯布局和双飞翼布局是前端工程师需要日常掌握的重要布局方式。两者的功能相同,都是为了实现一个两侧宽度固定,中间宽度自适应的三栏布局。
虽然说css3提供了flex布局之后,实现两侧固定,中间自适应已经变得很简单,但是对于传统的方法,依然很有必要了解一下

对于这两种实现的方式,都有用以下共同点:

  • 两侧宽度固定,中间宽度自适应
  • 中间部分在DOM结构上优先,以便先行渲染
  • 允许三列中的任意一列成为最高列
  • 只需要使用一个额外的
    标签

上述第二点是flex布局所没有的优势

圣杯布局

DOM结构

1
2
3
4
5
<div class="container">
<div class="main"></div>
<div class="left"></div>
<div class="right"></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
25
26
27
28
.container {
padding-left: 120px;
padding-right: 220px;
}
.main {
float: left;
width: 100%;
height:300px;
background: green;
}
.left {
position: relative;
left: -120px;
float: left;
height: 300px;
width: 100px;
margin-left: -100%;
background: red;
}
.right {
position: relative;
right: -220px;
float: right;
height: 300px;
width: 200px;
margin-left: -200px;
background: blue;
}

在上述代码中,由于padding的影响,我们单纯使用margin-left出来的效果是这样的

那是因为相对定位的包含块是父级元素的content-box,所以就算将元素移动上来,也会受到padding的影响而覆盖了部分main元素。但是我们可以使用包含块为padding-box的计算方式(绝对定位),使用left和right调整之后:

双飞翼布局

DOM结构:

1
2
3
4
5
<div class="content">
<div class="main"></div>
</div>
<div class="left"></div>
<div class="right"></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
25
26
27
28
29
30
31
32
.content {
float: left;
width: 100%;
}
.main {
height: 200px;
margin-left: 110px;
margin-right: 220px;
background: green;
}
.main::after {
content: '';
display: block;
font-size:0;
height: 0;
zoom: 1;
clear: both;
}
.left {
float:left;
height: 200px;
width: 100px;
margin-left: -100%;
background: red;
}
.right {
float: right;
height: 200px;
width: 200px;
margin-left: -200px;
background: blue;
}
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2021 AURORA_ZXH
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信