盒子模型是 CSS 佈局的基石。徹底理解標準盒模型、IE 盒模型差異、box-sizing 控制機制、margin 重疊規則,是解決 90% 佈局疑難雜癥的前提。
┌─────────────────────────────────────┐
│ Margin (外邊距) │ 透明、不計入寬高、可負值、垂直重疊
│ ┌───────────────────────────────┐ │
│ │ Border (邊框) │ │ 有寬度、顏色、樣式、圓角
│ │ ┌─────────────────────────┐ │ │
│ │ │ Padding (內邊距/填充) │ │ │ 背景色/圖片延伸至內邊距
│ │ │ ┌───────────────────┐ │ │ │
│ │ │ │ Content (內容區) │ │ │ │ 文字、圖片、子元素實際內容
│ │ │ │ width × height │ │ │ │
│ │ │ └───────────────────┘ │ │ │
│ │ └─────────────────────────┘ │ │
│ └───────────────────────────────┘ │
└─────────────────────────────────────┘
/* 全局重置:現代 CSS 重置標配 */
*, *::before, *::after {
box-sizing: border-box;
}
/* 三個值 */
box-sizing: content-box; /* 默認,標準盒模型 */
box-sizing: border-box; /* IE 盒模型,寬高含 padding+border */
box-sizing: inherit; /* 繼承父元素,便於組件隔離 */
width: 50%; padding: 10px; 穩定佔半容器| 方法 | 適用場景 | 副作用 |
|---|---|---|
父級 overflow: hidden/auto | 父子重疊 | 可能剪切內容/出現滾動條 |
父級 padding: 1px (或任意 >0) | 父子重疊 | 增加視覺間距 |
父級 border: 1px solid transparent | 父子重疊 | 無視覺影響 |
父級 display: flow-root | 父子重疊 (現代) | 無副作用,建立 BFC |
父級 float: left/right | 父子重疊 | 脫離文檔流,需清除浮動 |
父級 position: absolute/fixed | 父子重疊 | 脫離文檔流 |
兄弟間插入 <hr> / 空 div + clear | 兄弟重疊 | 增加 DOM 節點 |
改用 padding 替代 margin | 源頭避免 | 背景色延伸差異 |
BFC 是獨立渲染區域,內部元素不影響外部,外部不影響內部。BFC 可阻止 margin 重疊、包含浮動、阻止元素被浮動覆蓋。
float: left/right (非 none)position: absolute/fixeddisplay: inline-block / flex / grid / table-cell / table-caption / flow-rootoverflow: hidden/auto/scroll (非 visible)contain: layout/content/paint/strict (現代).col { width: 50%; padding: 20px; float: left; } /* 標準盒模型下撐大,換行 */
/* 修復 */
.col { box-sizing: border-box; }
img { display: block; } /* 或 vertical-align: bottom/middle/top */
/* 原因:圖片默認 inline-baseline 對齊,預留行高下沉空間 */
.flex-item { min-width: 0; } /* 允許壓縮小於內容寬度 */
.grid-item { min-width: 0; }
.parent { overflow: hidden; } /* 或 flow-root */
.child { margin-top: 20px; } /* 現在相對父元素內邊距生效 */
outline: 1px solid red; 不佔空間、不觸發重排,適合調試* { background: rgba(0,0,0,.03); } 快速可視化所有盒子範圍box-sizing: border-box(重置 CSS 首行)gap (Flex/Grid) 或 padding (容器內部)flow-root 建立 BFCdisplay: block 或 vertical-align