關鍵難點:左定右適應 + 等高 同時滿足。本文提供五種經典純CSS方案,均含完整代碼與Demo鏈接。
#left { float: left; width: 220px; background: green; }
#content { margin-left: 220px; background: orange; } /* 關鍵:margin等於左欄寬 */
簡潔直觀,右欄BFC自適應。
#left { float: left; width: 220px; margin-right: -100%; background: green; }
#content { float: left; width: 100%; }
#contentInner { margin-left: 220px; background: orange; }
右欄先佔滿寬,內層用margin-left騰出左欄空間,結構稍繁但擴展性強。
#wrapper {
display: inline-block;
border-left: 200px solid #d4c376; /* 左欄背景色塊 */
position: relative;
vertical-align: bottom; /* 關鍵:底部對齊觸發等高 */
}
#sidebar { float: left; width: 200px; margin-left: -200px; position: relative; }
#main { float: left; }
#main, #sidebar { min-height: 200px; height: auto !important; height: 200px; } /* IE6/7最小高度Hack */
利用inline-block元素基線對齊特性+巨大左邊框模擬左欄背景,vertical-align: bottom強制底部對齊實現等高。
#container { overflow: hidden; } /* 清除浮動+裁剪溢出 */
#left { float: left; width: 200px; margin-bottom: -99999px; padding-bottom: 99999px; background: #ccc; }
#content { margin-left: 200px; margin-bottom: -99999px; padding-bottom: 99999px; background: #eee; }
#left, #content { min-height: 200px; height: auto !important; height: 200px; }
極大padding-bottom撐高背景,極大負margin-bottom抵消佈局流影響,容器overflow:hidden裁剪溢出。兼容性極佳。
#container { overflow: hidden; padding-left: 220px; background: #0ff; }
#content { float: right; width: 100%; border-left: 220px solid #f00; margin-left: -220px; background: #0ff; }
#sidebar { float: right; width: 220px; margin-left: -220px; background: #f00; }
#content, #sidebar { min-height: 200px; height: auto !important; height: 200px; }
容器padding-left預留左欄空間,右欄float:right+負邊距回流,左欄背景通過右欄border-left繪製。思維反轉極具啟發性。
#container2 { float: left; width: 100%; background: orange; position: relative; overflow: hidden; }
#container1 { float: left; width: 100%; background: green; position: relative; left: 200px; }
#col1 { float: left; width: 200px; margin-left: -200px; position: relative; left: -200px; }
#col2 { float: left; width: 100%; }
雙層容器相對位移製造等高視覺,結構較重但邏輯清晰。
.container { display: flex; min-height: 200px; }
.sidebar { width: 200px; flex-shrink: 0; background: green; }
.main { flex: 1; background: orange; }
三行代碼完美解決所有需求:自適應、等高、最小高度、無Hack。現代項目首選Flexbox/Grid,歷史項目參考前四種方案。
| 場景 | 推薦方案 |
|---|---|
| 現代項目(IE10+) | Flexbox/Grid |
| 需兼容IE8-9 | 方案二(負Margin+Padding) |
| 需兼容IE6-7 | 方案二 + IE6/7 Hack |
| 教學/理解原理 | 方案一/三(展示CSS佈局精髓) |