三列布局中,最麻煩的往往不是分欄,而是「等高」——當三欄內容高度不一時,要讓背景色一路延伸到底,看起來像同高。這裡介紹一種經典做法:給每一欄加上巨大的 padding-bottom,再用等量的負 margin-bottom 抵消,最後由外層容器 overflow:hidden 裁掉多餘部分。
<body>
<div id="wrap">
<div id="left">
<p style="height:500px">style="height:500px"</p>
</div>
<div id="center">
<p style="height:600px">style="height:600px"</p>
</div>
<div id="right">
<p style="height:700px">style="height:700px"</p>
</div>
</div>
</body>
<style type="text/css">
* {
margin:0;
padding:0;
}
#wrap {
overflow:hidden;
width:1000px;
margin:0 auto;
}
#left, #center, #right {
margin-bottom:-10000px;
padding-bottom:10000px;
}
#left {
float:left;
width:250px;
background:#777;
}
#center {
float:left;
width:500px;
background:#888;
}
#right {
float:right;
width:250px;
background:#999;
}
p {color:#FFF;text-align:center}
</style>
三欄各自加上 10000px 的 padding-bottom,讓它們的背景一直向下延伸;同時用 -10000px 的 margin-bottom 把多佔的空間扣回來,於是網頁的實際高度仍然由內容最多的那一欄決定。最後外層 #wrap 設為 overflow:hidden,把超出部分裁掉,視覺上就得到三欄齊平的效果。
幾個實作提醒:padding 與 margin 的數值必須完全相同,否則會出現高度偏差;10000px 只是個足夠大的取值,可依實際情況調整;至於寬度,250 + 500 + 250 剛好等於 1000px,别忘了把任何 border 或 padding 計入總寬。
在現代項目中,這個需求直接用 flexbox 的 align-items: stretch(預設值)或 CSS Grid 就能一行解決,瞭解舊方案主要是為了維護老站點時不至于束手無策。