三欄等高是版面配置裡的經典難題:中欄要自適應寬度,左右兩欄固定,而且不論哪一欄內容比較長,三欄的背景都要拉到同樣的高度。純 CSS 沒有「等高」這個屬性,只能靠一些巧妙的組合去模擬。
這份實作改寫自國外流傳的 Holy Grail 版面範例,並補上 hack 讓它同時兼容 IE5.5 以上與 Opera、Firefox、Safari 等標準瀏覽器。老實說,為了兼顧這麼多環境,裡面的 hack 數量確實偏多,這也是這種做法一直被詬病的地方。
結構很乾脆:header、container(內含 center / left / right)、footer。中欄寫在最前面,左右欄後寫,靠負 margin 把它們拉到視覺上的正確位置。
<div id="header">header</div>
<div id="container">
<div id="center">中欄內容</div>
<div id="left">左欄內容</div>
<div id="right">右欄內容</div>
</div>
<div id="footer">footer</div>
* { margin:0; padding:0; }
body {
min-width: 550px;
font: normal 75%/1.25em Verdana, Arial, Helvetica, sans-serif;
color:#333333;
text-align:left;
}
/* 版面:左右留白等於兩欄寬度 */
#container {
padding-left: 200px;
padding-right: 150px;
background:#000;
zoom:1;
}
/* 清除浮動 */
#container:after {
content:'.';
display: block;
height: 0;
clear: both;
visibility: hidden;
}
#container { display: inline-block; }
/*\*/
#container { display: block; }
/*\*/
#center, #left, #right {
position: relative;
float: left;
}
#center { width: 100%; }
#left {
width: 200px;
right: 200px;
margin-left: -100%;
}
#right {
width: 150px;
margin-right: -150px;
}
#footer { clear: both; }
等高的原理是:給 container 加上 overflow:hidden 形成收斂,再用「極大的 padding-bottom 搭配等量的負 margin-bottom」把每欄的背景往下延伸,最後由 container 裁掉多餘的部分。
/* 等高本體 */
#container { overflow: hidden; }
#footer { overflow:hidden; position: relative; }
/* IE7 hack */
*+html #center, *+html #left, *+html #right { position: static; }
*+html #container { position:relative; overflow:hidden; }
*+html #left { position:relative; }
/* Opera8 hack */
/*\*/
#container #center, #container #left, #container #right {
padding-bottom: 32767px !important;
margin-bottom: -32767px !important;
}
@media all and (min-width: 0px) {
#container #center, #container #left, #container #right {
padding-bottom: 0 !important;
margin-bottom: 0 !important;
}
#center:before, #left:before, #right:before {
content: '[DO NOT LEAVE IT IS NOT REAL]';
display: block;
background: inherit;
padding-top: 32767px !important;
margin-bottom: -32767px !important;
height: 0;
}
}
/**/
三欄等高在純 CSS 時代確實是個經典題,但這份實作也示範了它的代價:為了填平各瀏覽器的差異,樣式裡塞滿了 hack,可讀性與維護性都打了折扣。如果今天重做同樣的需求,用 Flexbox 或 Grid 只要幾行就能搞定,也不需要任何 hack。把這份寫法當成理解浮動、負 margin 與 BFC 的教材,價值反而更高。