
正文
CSS经典布局——圣杯布局与双飞翼布局
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
一、圣杯布局和双飞翼布局的目的- 实现三栏布局,中间一栏最先加载和渲染
- 两侧内容固定,中间内容随着宽度自适应
- 一般用于PC网
二、圣杯布局的实现
技术要点:
- 设置最小宽度min-width
- 使用float布局,注意清除浮动
- 使用margin负值
- 对三栏整体区域设置左右内边距,宽度为left和right的宽度,避免内容重叠
- 使用定位


1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <meta http-equiv="X-UA-Compatible" content="IE=edge">
7 <meta name="viewport" content="width=device-width, initial-scale=1.0">
8 <title>圣杯布局</title>
9 </head>
10 <style>
11 body {
12 //设置屏幕最小宽度
13 min-width: 500px;
14 text-align: center;
15 }
16
17 header,
18 footer {
19 width: 100%;
20 background-color: grey;
21 }
22
23 section {
24 /*清除浮动*/
25 overflow: hidden;
26 /*左右设置内边距*/
27 padding-left: 150px;
28 padding-right: 200px;
29 }
30
31 #center {
32 width: 100%;
33 background-color: red;
34 }
35
36 #left {
37 /* 相对自身的定位 */
38 position: relative;
39 width: 150px;
40 /*向左平移一个父元素的宽度 */
41 margin-left: -100%;
42 /* 向左平移150px */
43 right: 150px;
44 background-color: pink;
45 }
46
47 #right {
48 width: 200px;
49 /* 可以当做right右侧元素向左平移200px,将right元素挤到上面一排显示。注:这里由于浮动,中间的元素都是连接在一起的,也就是说center与right是首尾相连的 */
50 margin-right: -200px;
51 background-color: yellow;
52 }
53
54 .culomn {
55 float: left;
56 }
57 </style>
58
59 <body>
60 <header>this is header</header>
61 <section>
62 <div id="center" class="culomn">this is center</div>
63 <div id="left" class="culomn">this is left</div>
64 <div id="right" class="culomn">this is right</div>
65 </section>
66 <footer>this is footer</footer>
67 </body>
68 </html>
三、双飞翼布局的实现
技术要点:
- 设置最小宽度min-width
- 使用float布局,注意清除浮动
- 使用margin负值(双飞翼布局不需要使用margin-right负值)
- 对center设置左右外边距,避免与侧边栏内容重叠
代码如下:


<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>双飞翼布局</title>
</head>
<style>
body {
min-width: 500px;
} header,
footer {
text-align: center;
width: 100%;
background-color: grey;
} #contain {
width: 100%;
} #center {
/* 对center元素设置左右外边距,分别是left和right元素的宽度,避免内容重叠 */
margin-left: 150px;
margin-right: 200px;
background-color: red;
} #left {
width: 150px;
/* left元素向左平移一个父元素的宽度 */
margin-left: -100%;
background-color: pink; } #right {
width: 200px;
/* right元素向左平移自身的宽度 */
margin-left: -200px;
background-color: yellow;
} .culomn {
float: left;
text-align: center;
} /* 清除浮动 */
footer {
clear: both;
}
</style><body>
<header>this is header</header>
<section>
<div id="contain" class="culomn">
<div id="center">this is center</div>
</div>
<div id="left" class="culomn">this is left</div>
<div id="right" class="culomn">this is right</div>
</section>
<footer>this is footer</footer>
</body></html>
圣杯布局与双飞翼布局效果图如下:

四、圣杯布局与双飞翼布局的区别- 圣杯布局使用了margin-right负值,相对来说比较难理解
- 圣杯布局设置的是内边距padding,避免内容重叠。而双飞翼布局是给center元素添加了一个父盒子,只需要设置center的外边距即可避免与左右侧边栏重叠
五、总结
圣杯布局和双飞翼布局的技术总结:
- 使用了float布局
- 两侧使用margin负值,以便和中间内容横向重叠
- 防止中间内容被两侧覆盖,一个用padding,一个用margin






