等高欄佈局是 CSS 經典難題:欄內容高度不一,背景色/邊框無法自然對齊底部。本文梳理從 Faux Columns (偽欄) 到 負 Margin + Border 填充、再到現代 Flexbox/Grid 的演進路徑,提供各時代最佳實踐代碼。
容器背景圖 repeat-y 繪製欄背景,內容實際不等高但視覺等高。缺陷:需圖片、不支援流體寬度、圓角/陰影難處理。
核心技巧:主欄加寬右邊框模擬側欄背景,負 Margin 將側欄拉入邊框區域。
#container { overflow: hidden; width: 750px; background: #0ff; }
#content {
width: 600px; float: left;
border-right: 150px solid #f00; /* 模擬側欄背景 */
margin-right: -150px; /* 拉入側欄 */
}
#rail { float: left; width: 150px; background: #f00; }
#container { float: left; width: 500px; background: #0ff;
border-left: 150px solid #0f0; /* 左欄背景 */
border-right: 200px solid #f00; /* 右欄背景 */
}
#center { float: left; width: 100%; margin-right: -500px; }
#left { float: left; width: 150px; margin-left: -150px; position: relative; }
#right { float: right; width: 200px; margin-right: -200px; position: relative; }
關鍵點:position: relative 修正 IE6/7 負 Margin 導致內容被遮蓋 Bug。
#container { overflow: hidden; margin: 0 100px; padding-right: 150px; }
* html #container { height: 1%; } /* IE6 hasLayout */
#content { width: 100%; float: left; border-right: 150px solid #f00; margin-right: -150px; }
#rail { float: left; width: 150px; margin-right: -150px; background: #f00; }
body { margin: 0 100px; padding: 0 200px 0 150px; } /* 預留左右欄空間 */
#container {
float: left; width: 100%; background: #0ff;
border-left: 150px solid #0f0; border-right: 200px solid #f00;
margin-left: -150px; margin-right: -200px; display: inline; /* IE6 雙倍邊距修復 */
}
#center { float: left; width: 100%; margin-right: -100%; }
#left { float: left; width: 150px; margin-left: -150px; position: relative; }
#right { float: right; width: 200px; margin-right: -200px; position: relative; }

**徹底解決等高、自適應、垂直居中、順序控制,零 Hack、零副作用。**
.container { display: flex; gap: 20px; }
.main { flex: 1; } /* 自適應寬度 */
.sidebar { width: 200px; } /* 固定寬度 */
/* 子元素自動等高,align-items: stretch (默認) */
.container {
display: grid;
grid-template-columns: 150px 1fr 200px; /* 固定/自適應/固定 */
gap: 20px;
grid-auto-rows: 1fr; /* 行高自動等高 */
}
| 項目環境 | 推薦方案 | 核心理由 |
|---|---|---|
| 現代項目 (IE10+ / 現代瀏覽器) | Flexbox / Grid | 語義化、零 Hack、功能最全、維護成本最低 |
| 需兼容 IE8-9 | Flexbox (配合 autoprefixer 2009 語法) 或 負 Margin 方案 | Flexbox 2009 版語法支援 IE10,IE8/9 需降級 |
| 需兼容 IE6/7 (極罕見) | 負 Margin + Border 填充 + position:relative Hack | 唯一可行的無 JS 方案 |
| 郵件模板 / 極受限環境 | Table 佈局 / Faux Columns | 表格天然等高,郵件客戶端支援最好 |
從 Table → Float + Hack → Flex/Grid,CSS 佈局歷程是**從「手工計算幾何」走向「聲明式約束」**的進化。新項目無理由不直接上 Flex/Grid;舊專案維護時,理解負 Margin 經典技巧依然是閱讀舊代碼的必備內功。