用 Div+CSS 做兩欄或三欄布局時,經常遇到一個難題:事先不知道各欄的實際高度,只能隨內容增減自適應,但你又希望幾欄看起來一樣高。
這件事用 table 輕而易舉,換成 div+css 就麻煩多了。常見做法有背景圖填充或 JS 腳本,但兩者都算不上漂亮——前者要多一張圖、後者要多一段程式。
下面介紹一個更乾淨的方案:「容器隱藏溢出」+「正內補丁」+「負外補丁」三者搭配。
#wrap {
overflow: hidden; /* 外容器 */
}
#sidebar_left, #sidebar_right {
padding-bottom: 100000px;
margin-bottom: -100000px; /* 各欄 */
}
關鍵在 padding 與 margin 那對相同數值、一正一負的組合:
padding-bottom: 100000px 讓每一欄的背景色向下延伸出一大段,確保視覺上都能填到底。margin-bottom: -100000px 把同樣的距離從排版高度中扣除,讓外容器仍只佔內容實際需要的高度。overflow: hidden 則把多餘溢出來的那一大截裁掉。三者合起來,就得到「背景等高、容器高度依內容」的效果。數值取得夠大(如 9999px),一般頁面都不會超出。
<!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=utf-8" />
<title>Div + CSS 等高欄範例</title>
<style type="text/css">
#wrap { overflow: hidden; }
#sidebar_left, #sidebar_right {
padding-bottom: 100000px;
margin-bottom: -100000px;
}
</style>
</head>
<body>
<div id="wrap" style="width:300px; background:#FFFF00;">
<div id="sidebar_left" style="float:left;width:100px; background:#FF0000;">Left</div>
<div id="sidebar_mid" style="float:left;width:100px; background:#666;">
Middle<br />
Middle<br />
Middle<br />
Middle<br />
Middle<br />
</div>
<div id="sidebar_right" style="float:right;width:100px; background:#0000FF;">Right</div>
</div>
</body>
</html>
左右兩欄內容很少,中間欄很長,但三欄的背景色依然齊平。已於 IE5.5、IE6、Firefox 1.5、Opera 9 測試通過。
因為外層依賴 overflow: hidden,這個容器內就不能再放需要外溢顯示的元素(如下拉選單)。若確有這種需求,可以退一步改用 clearfix 搭配背景偽元素,或直接把外層換成 another 包裹層來隔離裁切範圍。