什么是圣杯布局炉擅?
根據(jù) wikipedia詞條,圣杯指多列等高的網(wǎng)頁布局清女。因為目前的實現(xiàn)方法都存在局限碧查,而又很難找到一個最優(yōu)解,圣杯因此而得名。
holy-grail.png
在[Matthew Levine 的文章](In Search of the Holy Grail http://alistapart.com/article/holygrail) 中提到了圣杯的五個要求:
- 中間列寬度自適應(yīng)(fluid)忠售,兩邊列寬度固定
- 在源文檔(source)中传惠,中間列處于側(cè)邊兩列之前
- 任意一列都可以作為最高列
- 除了必要的元素之外,只多出一個div標(biāo)簽
- 用簡潔的CSS實現(xiàn)稻扬,盡量減少hack
Padding Solution
這個方法來自[Matthew Levine 的文章](In Search of the Holy Grail http://alistapart.com/article/holygrail)卦方。
實現(xiàn)思路:在三列之外包上一個div,通過padding留出左右列的空間泰佳,再通過 relative positon 把左右列移動到合適位置盼砍。
- 首先通過 float: left 把三個div排到同一行,并分別設(shè)置三列的寬度
- 在三列之外包上一個div逝她,設(shè)置其左右padding分別為左右列的寬度
- 對左列設(shè)置 margin-left: -100% 從而移動到最左側(cè)浇坐。通過 position: relative, right: [width_of_left_col] 把左列移動到padding留出的左側(cè)空間。
- 使用 position: relative, right: -[width_of_right_col] 把右列移動到padding留出的右側(cè)空間黔宛。
- 對 footer 設(shè)置 clear: both, 防止和三列重疊近刘。
- 中間列的最小寬度不能低于左列寬度。
// HTML
<div class="body">
<div class="header">header</div>
<div class="container">
<div id="center" class="column">
main
</div>
<div id="left" class="column">
nav
</div>
<div id="right" class="column">
ads
</div>
</div>
<div class="footer">footer</div>
</div>
// CSS
.body {
min-width: 600px;
}
.footer {
clear: both;
}
.container {
padding: 0 200px;
}
.column {
position: relative;
float: left;
}
#center {
width: 100%;
}
#left {
width: 200px;
margin-left: -100%;
right: 200px;
}
#right {
width: 200px;
margin-right: -200px;
}
Margin Solution
- 在center column外面套一層div臀晃,寬度為100%觉渴。
- 兩邊列和中間div都為float:left,使三列同行顯示徽惋。
- 對左列margin-left:-100%案淋,使其定位于最左的寬度。
- 中間列兩邊設(shè)置margin分別為左右列的寬度险绘。
- 右邊列設(shè)置margin-left為負(fù)自己的寬度踢京,使其縮進(jìn)wrapper里面
// HTML
<div class="header">header</div>
<div class="center-wrapper">
<div id="center">
main
</div>
</div>
<div id="left">nav</div>
<div id="right">ads</div>
<div class="footer">footer</div>
// CSS
.footer {
clear: both;
}
.center-wrapper {
float: left;
width: 100%;
}
#center {
margin: 0 200px;
}
#left {
float: left;
width: 200px;
margin-left: -100%;
}
#right {
float: left;
width: 200px;
margin-left: -200px;
}
Flexbox Solution
最簡單的實現(xiàn)方法。
<div class="header">header</div>
<div class="container">
<div id="center">
main
</div>
<div id="left">nav</div>
<div id="right">ads</div>
</div>
<div class="footer">footer</div>
.container {
display: flex;
}
#left {
width: 200px;
order: -1;
}
#right {
width: 200px;
}
#center {
flex: 1;
}
Follow-up
當(dāng)窗口很狹窄的時候宦棺,把左邊列移動到中間列之上瓣距,右邊列移動到中間列之下。
holy-grail-stack.png
// CSS
@media(max-width:600px){
.container{
flex-direction: column;
}
}