標準盒模型 vs IE 盒模型
| 模型 | width/height 含義 | 實際佔用寬度 |
| 標準 (W3C) | 內容區寬高 | width + padding + border + margin |
| IE 怪異模式 | 含 padding+border | width + margin |
box-sizing 統一模型
/* 全局推薦:所有元素採用 border-box */
*, *::before, *::after {
box-sizing: border-box;
}
/* 值對比 */
box-sizing: content-box; /* 標準模型 */
box-sizing: border-box; /* 寬高含 padding+border,不含 margin */
Margin/Padding 簡寫完整規則
/* 四值:上右下左(順時針) */
margin: 1px 2px 3px 4px;
/* 三值:上、左右、下 */
margin: 1px 2px 3px; /* = 1px 2px 3px 2px */
/* 兩值:上下、左右 */
margin: 1px 2px; /* = 1px 2px 1px 2px */
/* 一值:四方同值 */
margin: 1px; /* = 1px 1px 1px 1px */
/* 注意:無三值「上、右、下」左邊距缺失時用右邊距,非零 */
Margin 塌陷(合併)完整規則
發生條件(同時滿足)
- 常規流(非 float、absolute、fixed)
- 塊級元素
- 垂直方向相鄰 margin
- 無 padding、border、clear、BFC 隔離
三種合併場景
- 兄弟元素:取較大值
max(margin-bottom, margin-top)
- 父子元素:子 margin-top 傳遞給父級(父無 padding-top/border-top)
- 空塊級元素:自身高度 0,上下 margin 合併
阻止合併的方法
- 父級加
padding-top: 1px 或 border-top: 1px solid transparent
- 父級觸發 BFC:
overflow: hidden, display: flow-root, float: left
- 子級改為
display: inline-block 或浮動/定位
實戰:卡片組件間距系統
.card {
margin-bottom: 24px; /* 僅設置下外邊距,避免合併複雜度 */
}
.card:last-child { margin-bottom: 0; }
/* 或者使用 Gap(Flex/Grid 容器) */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 24px; /* 完美解決間距,無合併問題 */
}
相關延伸閱讀
CSS 註釋高級用法:準修飾選擇器、代碼標簽、繼承標記