本例實現上中下三行布局:上下定高,中間欄自適應瀏覽器高度,且內容垂直居中。
已通過 Firefox 2.0/Win、IE6/Win、IE7/Win、Opera 8.5 cn/Win、Safari 測試。
對於非 IE 核心瀏覽器,透過設定 display:table、display:table-row 與 display:table-cell 來模擬表格的表現形式。
最外層 #box 設為 { display:table; }、高度 100%,其子層 #header/#main/#footer 設為 { display:table-row; },如此便能模擬表格的行效果——上下定高,中間不定高的層自然自適應高度。
#wrap 層設為 { display:table-cell; } 模擬單元格,因此可以設定 { vertical-align:middle; } 實現垂直居中。
由於 Win IE 不支援 { display:table; },只能改用定位方式實現。<!--[if IE]> 內即是針對 IE 的設定。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<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>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
<p>內容內容</p>
</div>
</div>
</div>
<div id="footer">footer</div>
</div>
</body>
</html>