盒子模型是 CSS 版面核心,許多版面崩壞皆源於對 width/height 定義的誤解。本文用實例釐清標準盒模型計算邏輯與巢狀影響。
元素總寬度 = margin-left + border-left + padding-left + width + padding-right + border-right + margin-right
元素總高度 = margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom
關鍵:width/height 僅設定 content 區域,不包含 padding、border、margin。
<dl>
<dt>test of dt</dt>
<dd>test of dd</dd>
</dl>
dl { background: red; border: 10px solid #000; width: 100px; height: 100px; }
dt { background: yellow; }
dd { background: green; }
結果:dl 可視寬高 = 100px + 20px(border) = 120px。內容區維持 100px,邊框向外擴展。
margin 會疊加到父元素外部(margin collapsing),導致父元素位置位移。overflow: hidden/auto 或 padding: 1px 可建立 BFC 防止 margin 塌陷。padding 會撐大父元素內部空間(若父元素無固定高度)。* { box-sizing: border-box; }
啟用後,width/height 包含 padding + border,不含 margin。符合直覺、大幅減少版面計算錯誤,**現代專案強烈建議全域啟用**。
width = content,邊框內距向外加。width = content + padding + border,內距邊框向內吃。