box-sizing
屬性(content-box 與 border-box 的差異)content-box
(預設):width/height 只包含內容,不含 padding/border。border-box
:width/height 包含 padding 與 border,比較好控制大小。 <h1>CSS 盒模型示範</h1>
<div class="box box1">Box 1</div>
<div class="box box2">Box 2</div>
.box {
width: 200px;
height: 100px;
background-color: lightblue;
margin: 20px;
padding: 10px;
border: 5px solid darkblue;
}
.box1 {
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid blue;
margin: 10px;
box-sizing: content-box;
}
.box2 {
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid green;
margin: 10px;
box-sizing: border-box;
}
width
/height
→ ✅ 記得還有 padding 與 border 會影響大小content-box
→ ✅ 多數情境下 border-box
更好維護content-box
與 border-box
今天學到的「盒模型」讓我真正理解到 CSS 的世界不是只有顏色和字體,而是每個元素都有看不見的「邊界」。以前我常常覺得排版跑掉,原來問題多半是 margin 或 padding 搞混。
練習 content-box
與 border-box
之後,我覺得 border-box
比較直覺,因為寬高就包含了邊框和內距,不用再去算總大小。這對未來要做排版時會更好控制。
盒模型就像是網頁世界的「建築結構」,一旦理解清楚,就能更精準地堆疊和排列元素。這一步很基礎,但卻是往後排版魔法的根基。