一、聖杯布局和雙飛翼布局的目的
- 實現三欄布局,中間一欄最先加載和渲染
- 兩側內容固定,中間內容隨着寬度自適應
- 一般用於PC網
二、聖杯布局的實現
技術要點:
- 設置最小寬度min-width
- 使用float布局,注意清除浮動
- 使用margin負值(如果對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
