需求是這樣:頁首與頁尾固定高度,中間區塊自動填滿剩餘的視窗高度,且中間的文字內容垂直居中。以下代碼在 Firefox 2.0、IE6、IE7、Opera 8.5、Safari 下測試通過。
思路是:非 IE 瀏覽器用 display: table 系列屬性模擬表格行為;IE 則用絕對定位處理。
最外層 #box 設為 display: table 並給 100% 高度,其子層 #header、#main、#footer 設為 display: table-row,於是形成表格「列」的效果:上下定高,中間不定高的列自動撐開。#wrap 再設為 display: table-cell 模擬儲存格,就能使用 vertical-align: middle 做垂直居中。
Win IE 不支援 display: table,因此 header 與 footer 用絕對定位釘在上下兩端,中間內容則用「top: 50% 再上移自身高度一半」的經典手法垂直居中。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>上中下三行布局</title>
<style type="text/css">
* { margin: 0; padding: 0; }
html, body, #box {
height: 100%;
font: small/1.5 "微軟雅黑", serif;
}
body { text-align: center; }
#box {
text-align: left;
background: #666;
display: table;
width: 80%;
margin: 0 auto;
position: relative;
}
#box > div { display: table-row; }
#header, #footer { background: #fcc; height: 50px; }
#main { background: #ccf; }
#main #wrap {
display: table-cell;
background: #ffc;
vertical-align: middle;
}
#text { text-align: center; }
</style>
<!--[if IE]>
<style type="text/css">
#header, #footer {
width: 100%;
z-index: 3;
position: absolute;
}
#footer { bottom: 0; }
#main { height: 100%; z-index: 1; position: relative; }
#main #wrap { position: absolute; top: 50%; width: 100%; text-align: left; }
#main #text { position: relative; width: 100%; top: -50%; background: #ccc; }
</style>
<![endif]-->
</head>
<body>
<div id="box">
<div id="header">header</div>
<div id="main">
<div id="wrap">
<div id="text">
<p>內容內容</p>
<p>內容內容</p>
</div>
</div>
</div>
<div id="footer">footer</div>
</div>
</body>
</html>
這整段在現代 CSS 裡可以簡化到不可思議的程度:
body {
display: grid;
grid-template-rows: 50px 1fr 50px;
height: 100vh;
text-align: center;
}
header、main、footer 依序落在三列上,中間的 1fr 自動吃掉剩餘高度,內容垂直居中只要給 main 加上 display: grid; place-items: center; 即可。
不需要 display: table 模擬、不需要条件注释、不需要 50% 位移技巧。這正是 grid 出現後最值得高興的事:一個曾經需要兩套代碼才能解決的布局問題,如今是樣式表裡最簡單的一行。