萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

DIV+CSS 標準化佈局常用模式:從單欄到三欄的完整代碼庫

掌握經典 DIV+CSS 佈局模式,是理解現代 Flex/Grid 設計思想的基石。本文彙總單欄、兩欄、三欄、多行多欄等 10+ 種常見佈局的標準代碼,涵蓋 float、position、margin-auto 三大核心技術,並標註適用場景與現代替代方案。

核心佈局技術對比

技術定位模式特點現代替代
margin:auto正常流區塊水平置中、固定寬度容器Flex/Grid 置中
float浮動流多欄並排、文字環繞、需清除浮動Flex/Grid
position:absolute絕對定位脫離文檔流、精確座標、固定寬高Flex/Grid + margin:auto

佈局代碼庫

1. 單欄置中(經典容器)

body { margin: 0; text-align: center; } /* IE5 hack */
#container { width: 960px; margin: 0 auto; text-align: left; }

2. 兩欄:側邊欄 + 主內容

Float 方案(經典)

.wrapper { overflow: hidden; /* 清除浮動 */ }
.sidebar { float: left; width: 240px; }
.content { margin-left: 260px; } /* 寬度 + 間距 */

Flex 方案(現代)

.wrapper { display: flex; gap: 20px; }
.sidebar { flex: 0 0 240px; }
.content { flex: 1; }

3. 三欄:左側欄 + 主內容 + 右側欄

絕對定位方案(Holy Grail 前身)

.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; }

Float 方案(雙飛翼 / 聖杯佈局變體)

.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; }

Flex 方案(現代標準)

.container { display: flex; gap: 20px; }
.left { flex: 0 0 200px; }
.center { flex: 1; }
.right { flex: 0 0 200px; }

4. 多行多欄組合

Header + 三欄 + Footer

.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; }

5. 絕對定位三欄(固定高度場景)

#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%; }

經典 Float 佈局陷阱與修正

  1. 父容器高度塌陷 → overflow: hidden / Clearfix / display: flow-root
  2. IE6 雙倍邊距 → display: inline 於浮動元素
  3. 三像素間隙 → _margin-right: -3px (IE6 hack)
  4. 負邊距覆蓋內容 → 聖杯佈局需 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%+,消除清除浮動、負邊距、定位脫流等歷史包袱。理解經典模式原理,僅為維護舊代碼、面試通關、深度理解渲染機制。

copyright © 萬盛學電腦網 all rights reserved