Chrome DevTools 直觀展示:content → padding → border → margin
總寬度 = margin-left + border-left + padding-left + width
+ padding-right + border-right + margin-right
示例:
.example {
width: 200px; padding: 10px; border: 5px solid #000; margin: 20px;
}
標準瀏覽器渲染寬度:200 + 10×2 + 5×2 + 20×2 = 270px
IE6-IE8 (怪異模式) 將 width 視為邊框框尺寸:
IE 寬度 = 200 + 20×2 = 240px (內容區僅 260px - 30px = 230px? 實際 200 - 30 = 170px)
導致佈局嚴重偏移。
設定 box-sizing: border-box 讓 width/height 包含 padding 和 border,與 IE 早期模型一致,更符合直覺:
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
position: absolute):不佔據文檔流空間float):脫離常規流但影響文字環繞| 屬性 | 值範例 | 說明 |
|---|---|---|
box-orient | horizontal | vertical | 子元素排列方向 |
box-flex | 1, 2, 3... | 按比例分配剩餘空間,≥1 生效 |
box-direction | normal | reverse | 子元素排序方向 |
box-align | start | end | center | stretch | 垂直對齊 |
box-pack | start | end | center | justify | 水平對齊/分佈 |
box-sizing | content-box | border-box | 盒模型類型 |
box-shadow | h v blur spread color inset | 陰影效果 |
.container {
display: box;
box-align: stretch;
box-orient: vertical;
}
.container span { box-flex: 1; }
注意:外層需固定寬度,內層需建立 BFC (Block Formatting Context)。