掌握經典 DIV+CSS 佈局模式,是理解現代 Flex/Grid 設計思想的基石。本文彙總單欄、兩欄、三欄、多行多欄等 10+ 種常見佈局的標準代碼,涵蓋 float、position、margin-auto 三大核心技術,並標註適用場景與現代替代方案。
| 技術 | 定位模式 | 特點 | 現代替代 |
|---|---|---|---|
| margin:auto | 正常流 | 區塊水平置中、固定寬度容器 | Flex/Grid 置中 |
| float | 浮動流 | 多欄並排、文字環繞、需清除浮動 | Flex/Grid |
| position:absolute | 絕對定位 | 脫離文檔流、精確座標、固定寬高 | Flex/Grid + margin:auto |
body { margin: 0; text-align: center; } /* IE5 hack */
#container { width: 960px; margin: 0 auto; text-align: left; }
.wrapper { overflow: hidden; /* 清除浮動 */ }
.sidebar { float: left; width: 240px; }
.content { margin-left: 260px; } /* 寬度 + 間距 */
.wrapper { display: flex; gap: 20px; }
.sidebar { flex: 0 0 240px; }
.content { flex: 1; }
.container { position: relative; padding: 0 200px 0 200px; } /* 預留左右欄空間 */
.left { position: absolute; top: 0; left: 0; width: 180px; }
.center { width: 100%; }
.right { position: absolute; top: 0; right: 0; width: 180px; }
.main { float: left; width: 100%; }
.center { margin: 0 220px 0 220px; } /* 左右預留 */
.left { float: left; width: 200px; margin-left: -100%; }
.right { float: left; width: 200px; margin-left: -200px; }
.container { display: flex; gap: 20px; }
.left { flex: 0 0 200px; }
.center { flex: 1; }
.right { flex: 0 0 200px; }
.page { display: flex; flex-direction: column; min-height: 100vh; }
.header { flex: 0 0 auto; }
.body { display: flex; flex: 1; gap: 20px; }
.footer { flex: 0 0 auto; }
#left { position: absolute; top: 0; left: 0; width: 120px; height: 100%; }
#middle { margin: 0 130px; height: 100%; }
#right { position: absolute; top: 0; right: 0; width: 120px; height: 100%; }
overflow: hidden / Clearfix / display: flow-rootdisplay: inline 於浮動元素_margin-right: -3px (IE6 hack)position: relative 配合 padding 預留/* 統一遷移模式 */
.old-float-layout {
/* float + clearfix + margin hack */
}
.new-flex-layout {
display: flex;
flex-wrap: wrap; /* 響應式換行 */
gap: 20px; /* 間距 */
align-items: stretch; /* 等高欄 */
}
.new-grid-layout {
display: grid;
grid-template-columns: 200px 1fr 200px; /* 三欄 */
gap: 20px;
/* 響應式 */
@media (max-width: 768px) {
grid-template-columns: 1fr;
}
}
總結:經典 Float/Position 佈局是 CSS 歷史的重要篇章。現代開發請直接使用 Flexbox(一維) 與 Grid(二維),代碼量減少 60%+,消除清除浮動、負邊距、定位脫流等歷史包袱。理解經典模式原理,僅為維護舊代碼、面試通關、深度理解渲染機制。