Css Box Model
規定了Element
處理元素Content
、Padding
、border
、margin
的方式 。
Box Model基本概念
這張圖就是在說明一個Element
元素的Box Model
,紅色框範圍內表代為Element
內的各屬性距離,而橘色框的代表Element
與Element
之間的距離。
來看看下列的Html與Css
<!-- html -->
<div class="box1">Box 1</div>
<div class="box2">Box 2</div>
--------------------------------
<!-- Css -->
.box1{
padding:10px;
border: 5px solid red;
margin:10px
}
顯示如下,其中Box 1
文字到框線的距離為padding 10px
,然後框線的寬度為5px
,
最後Box1
和Box2
的距離為margin 10px
。
Chrome Tools
的 Elements Style
的結果如下。
Box Model的寬度
如果在一個Element
設置width
,那麼該Element
的寬度是指Box Model
的那個範圍呢??根據W3C的標準定義Content Width
,如下面Css我們在增加width:500px
屬性。
.box1{
width:500px;
padding:10px;
border: 5px solid red;
margin:10px
}
結果如下,width:500px
所指的為content width
,也就是Element
的內容寬度。
Box-Sizing屬性
在上一段文章中有提到,在Element
上增加width
屬性實際上是指content width
,
所以有時後有人會很疑惑,明明寬度設了500px
或XXXpx
卻還是超過,這往往是Box Model
不熟悉的問題。
而Box-Sizing
屬性的border-box
值,就是指將width
屬性從content width
改成content + padding + border 的 with
,如下Css,我們新增加了box-sizing : border-box
。
.box1{
box-sizing : border-box
width:500px
padding:10px;
border: 5px solid red;
margin:10px
}