详解圣杯和双飞翼布局

前言

首先,圣杯布局和双飞翼布局都是要解决同一个问题,它们实现的都是两边固定,中间自适应的三栏布局,也就是固-比-固布局。圣杯布局和双飞翼布局的主要差别在于其各自实现的思想不同,最终所实现的效果都是一样的。

圣杯布局

实现代码如下:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>圣杯布局示例</title>
</head>
<style>
/*防止浏览器屏幕过小而破坏布局*/
body {
min-width: 600px;
}
.header,
.footer {
height: 50px;
background-color: gray;
}
.wrapper {
padding-left: 210px;
padding-right: 190px;
overflow: hidden;
zoom: 1;
}
.wrapper .main {
float: left;
width: 100%;
height: 300px;
background-color: yellow;
}
.wrapper .left {
position: relative;
left: -210px;
float: left;
width: 200px;
height: 300px;
margin-left: -100%;
background-color: skyblue;
}
.wrapper .right {
position: relative;
right: -190px;
float: left;
width: 180px;
height: 300px;
margin-left: -180px;
background-color: red;
}
</style>
<body>
<header class="header">header</header>
<div class="wrapper">
<div class="main">main</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
<footer class="footer">footer</footer>
</body>
</html>

实现思路:子元素统一左浮动,左右两栏通过负的外边距来与中间一栏保持对齐,然后通过父元素的内边距和左右两栏的相对定位实现三栏布局。
优点:主要内容优先加载,没有多余div,允许任何列是最高的,兼容性好。

双飞翼布局

实现代码如下:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>淘宝双飞翼布局示例</title>
</head>
<style>
.header,
.footer {
height: 50px;
background-color: gray;
}
.wrapper {
overflow: hidden;
zoom: 1;
}
.wrapper .main-wrapper {
float: left;
width: 100%;
}
.wrapper .main-wrapper .main {
height: 300px;
margin: 0 190px 0 210px;
background-color: yellow;
}
.wrapper .left {
float: left;
width: 200px;
height: 300px;
margin-left: -100%;
background-color: skyblue;
}
.wrapper .right {
float: right;
width: 180px;
height: 300px;
margin-left: -180px;
background-color: hotpink;
}
</style>
<body>
<header class="header">header</header>
<div class="wrapper">
<div class="main-wrapper">
<div class="main">main</div>
</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
<footer class="footer">footer</footer>
</body>
</html>

实现原理:子元素统一左浮动,左右两栏通过负的外边距来与中间一栏保持对齐,中间栏增加父容器,然后利用中间栏的外边距进行定位。
优点:主要内容优先加载,兼容性比圣杯布局好,实现了内容与布局的分离,主元素宽度自适应,减少了相对定位。