三行二列的版型中,「每欄高度一致」幾乎是所有設計者都想解決的問題——而且內容高度事先無法預知。常見做法有背景圖填充、加一段 JS 來計算高度。本文介紹的是另一條路:容器隱藏溢出,再讓欄位同時使用極大的 bottom padding 與等量的負 bottom margin。
#wrap {
overflow: hidden;
}
#sideleft, #sideright {
padding-bottom: 32767px;
margin-bottom: -32767px;
}
這個技巧由四個條件構成:
1. 塊元素必須放在一個容器裡。
2. 容器套用 overflow: hidden。
3. 欄位塊元素套用一個足夠大的 padding-bottom。
4. 同一元素再套用等量的負 margin-bottom。
padding-bottom 把欄位往下撐長,讓它看起來與最高的欄一樣高;負的 margin-bottom 又把元素拉回原本底部開始的位置,因此後續元素不會被推開;而多溢出來的那段,就被容器的 overflow: hidden 裁掉了。三者缺一不可。
它會算出錯誤的高度,因此需要用註解技巧把規則隔離掉:
/*/*/
#sideleft, #sideright {
padding-bottom: 32767px;
margin-bottom: -32767px;
}
/**/
Opera 7.0~7.2 無法正確清除溢出部分,需要補一段 easy clearing:
/* easy clearing */
#wrap:after {
content: '[DO NOT LEAVE IT IS NOT REAL]';
display: block;
height: 0;
clear: both;
visibility: hidden;
}
#wrap {
display: inline-block;
}
/*/*/ #wrap { display: block; } /* end easy clearing */
Opera 8 在處理 overflow: hidden 時另有 bug,還得再加上:
/*/*/ #sideleft, #sideright {
padding-bottom: 32767px !important;
margin-bottom: -32767px !important;
}
@media all and (min-width: 0px) {
#sideleft, #sideright {
padding-bottom: 0 !important;
margin-bottom: 0 !important;
}
#sideleft:before, #sideright:before {
content: '[DO NOT LEAVE IT IS NOT REAL]';
display: block;
background: inherit;
padding-top: 32767px !important;
margin-bottom: -32767px !important;
height: 0;
}
}
/**/
Opera 9 的 B2 版本則修正了 8 的這個 bug。
原文以 IE 5.01、IE 5.5、IE 6.0、Firefox 1.5、Opera 8.5、Netscape 7.2 測試通過。
值得補充的是,如果今天只需要支援現代瀏覽器,同樣的效果用 display: table / table-cell,或直接上 Grid、Flexbox,程式碼會乾淨得多,也不必再背上面那一串 hack。